在包含 Camera 实例的 surfaceView 上,您必须实现一些方法。其中之一是surfaceChanged。在该方法中,您应该按如下方式更新方向:
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
...
this.setCameraDisplayOrientation(this.cameraId, this.mCamera);
...
}
以及实现:
/**
* Calling this method makes the camera image show in the same orientation as the display.
* NOTE: This method is not allowed to be called during preview.
*
* @param cameraId
* @param camera
*/
@SuppressLint("NewApi")
public void setCameraDisplayOrientation(int cameraId, android.hardware.Camera camera) {
int rotation = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0: degrees = 0; break;
case Surface.ROTATION_90: degrees = 90; break;
case Surface.ROTATION_180: degrees = 180; break;
case Surface.ROTATION_270: degrees = 270; break;
}
int result;
if (Utils.hasGingerbread()) {
android.hardware.Camera.CameraInfo info =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
} else {
// on API 8 and lower devices
if (context.getResources().getConfiguration().orientation !=Configuration.ORIENTATION_LANDSCAPE) {
result = 90;
} else {
result = 0;
}
}
try {
camera.setDisplayOrientation(result);
} catch (Exception e) {
// may fail on old OS versions. ignore it.
e.printStackTrace();
}
}