重新启动自定义相机,同时更改预览模式,从横向到纵向或纵向到横向 strong>,我的Surface类代码如下所示:
PreviewSurface.java: -
public class PreviewSurface extends SurfaceView implements
SurfaceHolder.Callback {
public static final String LOG_TAG = "CameraPreview";
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
// Constructor that obtains context and camera
@SuppressWarnings("deprecation")
public PreviewSurface(Context context, Camera camera) {
super(context);
this.mCamera = camera;
this.mSurfaceHolder = this.getHolder();
this.mSurfaceHolder.addCallback(this);
this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
this.mSurfaceHolder.setFixedSize(100, 100);
}
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
Camera.Parameters parameters = mCamera.getParameters();
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE)
{
parameters.set("orientation", "portrait");
mCamera.setDisplayOrientation(90);
parameters.setRotation(90);
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
}
else
{
// This is an undocumented although widely known feature
parameters.set("orientation", "landscape");
// For Android 2.2 and above
mCamera.setDisplayOrientation(0);
// Uncomment for Android 2.0 and above
parameters.setRotation(0);
}
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
// left blank for now
}
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
mCamera.stopPreview();
mCamera.release();
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
try {
Camera.Parameters parameters = mCamera.getParameters();
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
parameters.set("orientation", "portrait");
mCamera.setDisplayOrientation(90);
parameters.setRotation(90);
}
else {
// This is an undocumented although widely known feature
parameters.set("orientation", "landscape");
// For Android 2.2 and above
mCamera.setDisplayOrientation(0);
// Uncomment for Android 2.0 and above
parameters.setRotation(0);
}
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
// left blank for now
}
}
}
我可以知道我在哪里做错了,我在代码中错过了什么?
答案 0 :(得分:12)
您必须为您的应用处理配置更改。
将此行添加到AndroidManifest.xml。
android:configChanges="keyboardHidden|orientation|screenSize"
这告诉系统您将自己处理哪些配置更改 - 在这种情况下无需执行任何操作。
希望它有助于ツ
答案 1 :(得分:0)
从你的问题不清楚你抱怨什么,但你似乎只操纵相机参数,从不打电话给mCamera.setParameters(parameters)
。仅这一点可能会引起混淆。
在不支持此参数的设备上使用parameters.set("orientation", "landscape");
可能会导致mCamera.setParameters(parameters)
中出现 RuntimeException 。因此,我们通常会使用单独的尝试来捕捉此设置。