Skew image with aspect ratio of Camera Preview

2019-08-30 03:00发布

问题:

I'm facing problem of skew image on camera preview.

My aim is to scale and fill out camera preview on its container (FrameLayout).

I'm very confusing that when I setPreviewSize() as 16:9 and when I try to stretch image on the FrameLayout by setting its size as 16:9 (this view may bigger than display screen size to fill out entire area of screen) image on camera preview start to skew.

However, if I setPreviewSize() as 16:9 and FrameLayout as 4:3 image on camera preview not skew at all.

Ex.Secenario #1 Image Skew

preview size -> w: 1920 h: 1080 (16:9) 

display size -> w: 1774 h:1080 (887:540) 

container size -> w: 1920 h: 1080 (16:9)

Ex.Secenario #2 Image Not Skew

preview size -> w: 1920 h: 1080 (16:9)

display size -> w: 1774 h:1080 (887:540)

container size -> w: 1800 h: 1350 (4:3)

So, what is the relationship between aspect ratio of camera preview and its container (FrameLayout) I quite confusing now why 16:9 preview size is not compatible with container size of 16:9. or I miss understand somethings please advice.

回答1:

I found out that the unexpected behavior is come from not include following code.. in surfaceChanged()

@Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        try {
            mCamera.stopPreview();
        } catch (Exception e){
            // ignore: tried to stop a non-existent preview
        }

        // Before do any configuration to camera
        // StopPreview() and StartPreview()
        // after finish it

        try {
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();
        } catch (Exception e){
            Log.d(TAG, "Error starting camera preview: " + e.getMessage());
        }

}

Important: Some camera features cannot be changed at will. In particular, changing the size or orientation of the camera preview requires that you first stop the preview, change the preview size, and then restart the preview. Starting with Android 4.0 (API Level 14) preview orientation can be changed without restarting the preview.

I just misunderstand of this Important note from android document. So, if you use stop and then configure your camera preview resolution or adjust your parent layout as same as aspect ratio of camera preview. After start preview, skew image preview won't happen.