我需要实现OrientationEventListener
才能让相机正常工作。 Google发布了onOrientationChanged
的示例实现,如下所示:
@Override
public void onOrientationChanged(int orientation) {
if (orientation == ORIENTATION_UNKNOWN) return;
android.hardware.Camera.CameraInfo info =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
orientation = (orientation + 45) / 90 * 90;
int rotation = 0;
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
rotation = (info.orientation - orientation + 360) % 360;
} else { // back-facing camera
rotation = (info.orientation + orientation) % 360;
}
mParameters.setRotation(rotation);
}
但我建立的是针对API级别8,因此我没有CameraInfo
。如何在没有CameraInfo
的情况下完成与上述相似的事情?
答案 0 :(得分:2)
虽然方向发生了变化,但我发现我还必须更改相机预览才能匹配,如果你想要旋转全屏图像,那么我使用类似的方法但是在相机表面视图的onLayout()方法中这样:
/*
* This class provides the surface for the camera.
*/
public class CameraSurfaceView extends ViewGroup implements SurfaceHolder.Callback
{
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom)
{
if (changed)
{
final int width = right - left;
final int height = bottom - top;
int previewWidth = width;
int previewHeight = height;
if (mPreviewSize != null)
{
Display display = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
switch (display.getRotation())
{
case Surface.ROTATION_0:
previewWidth = mPreviewSize.height;
previewHeight = mPreviewSize.width;
mCamera.setDisplayOrientation(90);
break;
case Surface.ROTATION_90:
previewWidth = mPreviewSize.width;
previewHeight = mPreviewSize.height;
break;
case Surface.ROTATION_180:
previewWidth = mPreviewSize.height;
previewHeight = mPreviewSize.width;
break;
case Surface.ROTATION_270:
previewWidth = mPreviewSize.width;
previewHeight = mPreviewSize.height;
mCamera.setDisplayOrientation(180);
break;
}
}
final int scaledChildHeight = previewHeight * width / previewWidth;
cameraView.layout(0, height - scaledChildHeight, width, height);
}
}
}
这对我使用Android API 8(Android 2.2)的HTC Desire有用。
答案 1 :(得分:1)
public void onOrientationChanged(int orientation) {
if (orientation == ORIENTATION_UNKNOWN) return;
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;
}
parameters.setRotation(degrees );
mcamera.setParameters(parameters);
}
希望这有帮助。
编辑: 请参阅相机应用程序源代码以了解它们如何处理它。此链接是最新的来源。可以返回修订版并查看2.2版本 Camera source
编辑:以下是2.2版本附近其中一个版本的链接。在此文件中搜索onOrientationChanged
:Camera src