我查阅了一些关于使用表面 View 更改相机方向的帖子,但我从以下示例中获取了我的代码:
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/graphics/CameraPreview.html
提供维度的函数看起来像这样......
private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.1;
double targetRatio = (double) w / h;
if (sizes == null) return null;
Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
// Try to find an size match aspect ratio and size
for (Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
// Cannot find the one match the aspect ratio, ignore the requirement
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
我的问题是,当我改变设备的方向时,预览图片保持横向。我尝试设置相机的方向,但这导致了非常奇怪的结果。有谁知道我需要更改什么才能正确旋转?
最佳答案
正确调整相机预览方向的代码有点复杂,因为它必须考虑
- 传感器的相对方向和设备的“自然”方向(通常是手机纵向,平板电脑横向)
- 设备的当前 UI 方向(纵向、横向或各自的反方向)
- 有问题的摄像头是前置摄像头还是后置摄像头(因为前置预览流是水平镜像的)
Camera.setDisplayOrientation 的文档有关于如何正确处理这个问题的示例代码。我在这里复制它:
public static 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;
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;
}
camera.setDisplayOrientation(result);
}
在绘制 UI(onSurfaceChanged 将用作指示器)或设备 UI 旋转(onConfigurationChanged 将用作指示器)后调用此函数。
关于android - 将 Camera SurfaceView 旋转为纵向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7455399/