我正在尝试使用SurfaceView
创建相机预览,它大部分工作正常。我在onSurfaceCreated
方法上初始化相机并在onSurfaceDestroyed
上销毁它。为什么在设备方向改变时调用上述方法。以下是表面视图代码。
@Override
public void surfaceCreated(SurfaceHolder holder) {
// Initialize the camera
initCamera();
Log.d("tags", "Camera Started!");
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (camera != null) {
camera.stopPreview();
camera.release();
}
Log.d("tags", "Camera destroyed!");
}
public void initCamera() {
if (camera == null) {
camera = Camera.open(); // Get's the first camera
}
try {
camera.setPreviewDisplay(sfHolder);
} catch (IOException err) {
err.printStackTrace();
}
// Set camera orientation
Activity activity = (Activity)this.getContext();
this.setCameraDisplayOrientation(activity);
camera.startPreview();
}
private void setCameraDisplayOrientation(Activity activity) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().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 (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;
}
Log.d("tag", "Result -- " + result);
boolean camNull = camera == null;
Log.d("tag", String.valueOf(camNull));
camera.setDisplayOrientation(result);
当我在设备上启动应用程序时,预览会按预期启动,但是当我将方向从纵向更改为横向,反之亦然时,预览会挂起几秒钟,并且新预览会显示更改的方向。 / p>
根据日志,当方向改变时,表面被破坏并再次创建,因此每次方向改变时都会重新初始化摄像机。我怎么能克服这个?我在这里做错了吗?