相机预览需要一些时间来重新定位方向更改

时间:2014-01-24 03:05:33

标签: android camera screen-orientation preview

我正在开发一款自定义相机Android应用。它可以正常工作,预览屏幕与纵向和横向模式下的屏幕尺寸非常吻合。但是,在更改手机方向时,预览重绘会有明显的延迟。通过论坛搜索,我遇到了其他人在处理电话更改时遇到类似问题。根据一些建议,以避免活动被破坏和重新创建,并在此类更改期间释放和打开相机,我已将以下行添加到AndroidManifest.xml:

        android:configChanges="orientation|screenSize">

通过一些调试和测试,我可以确认在方向更改时不再销毁/创建活动。但是,即使有这样的添加,当预览重绘从纵向到横向时也会有明显的延迟,反之亦然。以下是Activity类中onConfigurationChanged方法的代码:

public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    mPreview.setCameraDisplayOrientation(this, 1, mCamera);
}

在SurfaceView类中:

public void setCameraDisplayOrientation(Activity activity,
        int cameraId, android.hardware.Camera camera) {

    android.hardware.Camera.CameraInfo info =
            new android.hardware.Camera.CameraInfo();
    android.hardware.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 = (info.orientation + degrees) % 360;
    result = (360 - result) % 360;  // compensate the mirror
    camera.setDisplayOrientation(result);
}

在surfaceChanged中,我有:

public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    initialisePreview(w, h); // gets best preview size and sets camera parameters
    mCamera.startPreview();
    }

上述setCameraDisplayOrientation方法没有任何新内容,并且是从Android开发者网站改编而来的。我不确定还有什么可能导致重绘这种延迟。如果有人有任何想法,请告知。谢谢。

1 个答案:

答案 0 :(得分:1)

如上所述,我没有处理屏幕方向更改,而是使用以下方式调用活动忽略由方向传感器确定的方向更改:

onCreate()

通过此更改,当手机方向发生变化时,预览将继续无缝连接。这个sppears反直觉,但它解决了我的问题。希望它可以帮到某人。