修复Android相机应用宽高比和旋转

时间:2013-06-10 21:53:30

标签: android android-camera surfaceview aspect-ratio

它看起来如何: http://i41.tinypic.com/30278m1.png

看起来像在pic中,我希望它具有正确的宽高比和正确的旋转

请看一下代码,我该如何解决?

这是我的代码:

    public class MainActivity extends Activity implements SurfaceHolder.Callback {

Camera mCamera;
SurfaceView mPreview; 

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mPreview = (SurfaceView)findViewById(R.id.preview);
    mPreview.getHolder().addCallback(this);
    mPreview.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    mCamera = Camera.open();
}   
@Override
public void onPause() {
    super.onPause();
    mCamera.stopPreview();
}    
@Override
public void onDestroy() {
    super.onDestroy();
    mCamera.release();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    Camera.Parameters params = mCamera.getParameters();
    List<Camera.Size> sizes = params.getSupportedPreviewSizes();
    Camera.Size selected = sizes.get(0);
    params.setPreviewSize(selected.width,selected.height);
    mCamera.setParameters(params);
    mCamera.startPreview();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
    try {
        mCamera.setPreviewDisplay(mPreview.getHolder());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    Log.i("PREVIEW","surfaceDestroyed");
}
}

1 个答案:

答案 0 :(得分:8)

使用以下方法更改surfaceChanged方法:

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {       
    Parameters parameters = mCamera.getParameters();
    List<Camera.Size> previewSizes = parameters.getSupportedPreviewSizes();
    Camera.Size previewSize = previewSizes.get(4); //480h x 720w

    parameters.setPreviewSize(previewSize.width, previewSize.height);
    parameters.setFlashMode(Parameters.FLASH_MODE_AUTO);
    parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);

    mCamera.setParameters(parameters);

    Display display = ((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    if(display.getRotation() == Surface.ROTATION_0) {                        
        mCamera.setDisplayOrientation(90);
    } else if(display.getRotation() == Surface.ROTATION_270) {
        mCamera.setDisplayOrientation(180);
    }

    mCamera.startPreview();
}

我希望我能帮到你!