Fitting a camera preview to a SurfaceView larger than the display

前端 未结 1 1111
予麋鹿
予麋鹿 2020-12-02 12:50

I have an Android application that needs to fullscreen a camera preview regardless of the preview size given by getSupportedPreviewSizes() without distortion. I

相关标签:
1条回答
  • 2020-12-02 13:00

    Ok, I know this is very late as an answer but it is possible. Below is code from the Android SDK sample. To see the rest of the code to implement this download the android sdk samples and go to Samples/android-10(one I used, could try whichever you want to target)/ApiDemos/src/com/example/android/apis/graphics/CameraPreview.java

    class PreviewSurface extends ViewGroup implements SurfaceHolder.Callback {
    ...
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (changed && getChildCount() > 0) {
            final View child = getChildAt(0);
    
            final int width = r - l;
            final int height = b - t;
    
            int previewWidth = width;
            int previewHeight = height;
            if (mPreviewSize != null) {
                previewWidth = mPreviewSize.width;
                previewHeight = mPreviewSize.height;
            }
    
            // Center the child SurfaceView within the parent.
            if (width * previewHeight > height * previewWidth) {
                final int scaledChildWidth = previewWidth * height / previewHeight;
                child.layout((width - scaledChildWidth) / 2, 0,
                        (width + scaledChildWidth) / 2, height);
            } else {
                final int scaledChildHeight = previewHeight * width / previewWidth;
                child.layout(0, (height - scaledChildHeight) / 2,
                        width, (height + scaledChildHeight) / 2);
            }
        }
    }
    }
    

    this code is intended to fit the preview to the smallest dimension (that doesn't mess up the aspcect ratio) and center to have black bars on the other dimension. But if you flip the > to be < instead you will achieve what you want. Ex:

    if (width * previewHeight < height * previewWidth) {...
    
    0 讨论(0)
提交回复
热议问题