Camera camera preview is not Proper after setdispl

2019-04-11 10:19发布

问题:

i m trying to implement camera in my app but i found that the orientation preview is all time in landscape but my app is in portrait so i need it in to portrait mode i found some solutions about that like

mCamera.setDisplayOrientation(90); 

its working good with Galaxy tab2 and htc but when i test it in sony xperia sola it display strange hear i add image screen of it

u can see that the preview of camera its display of right side of screen only

but when i take picture from this app it display ok. i don't no what is the problem can anyone help me in this .

回答1:

You can try to force the surface size (and position) - I followed this path to compensate a similar bug in 2.2 version of Samsung Galaxy S. The bug was fixed when the device upgraded to 2.3.



回答2:

I solved this using the following code:

class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {

    [...]

    public void show(){
        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        if (!showing) {
            showing=true;
            try {
                mCamera = Camera.open();
                aspectRatio();

                try {
                    mCamera.setPreviewDisplay(mHolder);
                    mCamera.startPreview();
                    mCamera.setDisplayOrientation(90);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(getContext(), R.string.text_camera_open_error, Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void aspectRatio(){
        if (!aspect_radio_corrected){
            aspect_radio_corrected=true;
            Display default_disp=((Activity)getContext()).getWindowManager().getDefaultDisplay();

            Camera.Parameters parameters = mCamera.getParameters();
            Camera.Size optimalPreviewSize=parameters.getPreviewSize();

            FrameLayout.LayoutParams l_params=(FrameLayout.LayoutParams)getLayoutParams();
            float ratio = (float) optimalPreviewSize.height / optimalPreviewSize.width;
            l_params.width=default_disp.getWidth();
            l_params.height=Math.round(l_params.width / ratio);
            setLayoutParams(l_params);
            requestLayout();
        }
    }

    [...]
}

And on the layout file I have:

<com.socialcoaster.utils.CameraPreview
    android:id="@+id/cameraView"
    android:background="@android:color/transparent"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Seems that this is a bug related with the aspect ratio of the current preview size setup on camera and the surfaceView area to show it. You can see that by simply changing the values of aspectRatio() to some fixed values like 100.