duan danny
duan danny

Reputation: 11

Use a custom Surface to render CameraX's Preview data

I'm using the CameraX component in Android, and according to the Android documentation, I can use Preview.setSurfaceProvider() to set up the rendering interface. However, I do not want to render it on the PreviewView component; I want to render the camera preview onto a custom-defined Surface. I have tried many ways, but none of them work. I hope to get help from everyone, thank you

I create a Surface in a customized way

Activity:

Surface mPreviewSurfaces;
private int textureIds = 0;

public boolean InitTexture()
{
    //by GL
    int videoTextureId = FBOUtils.createOESTextureID();
    textureIds = videoTextureId;
    if (mSurfaceTexture != null) {
        mSurfaceTexture.release();
    }

    mSurfaceTexture = new SurfaceTexture(textureIds);
    TextureListenser listenser = new TextureListenser();
    mSurfaceTexture.setDefaultBufferSize(1280, 720);
    mSurfaceTexture.setOnFrameAvailableListener(null);
    mSurfaceTexture.setOnFrameAvailableListener(listenser);
    mPreviewSurfaces = new Surface(mSurfaceTexture);
    return true;
}

Create a service, configure and start a CameraX

Service: Preview.Builder builder = new Preview.Builder(); builder.setTargetRotation(Surface.ROTATION_90); builder.setResolutionSelector(resolutionSelector); _PreviewUseCase = builder.build();

    Surface mSurface = CameraXApp.get_Surface();

    _PreviewUseCase.setSurfaceProvider(request -> {
                Size resolution = request.getResolution();
                Log.d("Camera", "Requested resolution: " + resolution.getWidth() + "x" + resolution.getHeight());

                if (mSurface != null && mSurface.isValid()) {
                    Log.d("Camera", "surface.....");
                }

                assert mSurface != null;
                request.provideSurface(
                        mSurface,
                        ContextCompat.getMainExecutor(mActivity),
                        result -> { 
                            Log.d(TAG, "surface complete");
                        }
                );
    });

    _CameraProvider.bindToLifecycle(/* lifecycleOwner= */ (LifecycleOwner)mActivity, _CurrentCameraSelector, _PreviewUseCase);

This program runs, and through the logs, I found that 'surface complete' is not printed out, and I cannot get the result through 'result'. I don’t know where the error is, and I hope everyone can give me some hints. Note that this code works correctly and displays the preview screen through _PreviewUseCase.setSurfaceProvider(R.id.PreviewView).

Upvotes: 1

Views: 13

Answers (0)

Related Questions