android.hardware.camera 实现预览镜像
时间: 2023-11-25 16:07:20 浏览: 155
要在 Android 相机预览中实现镜像,可以使用 `Camera.setDisplayOrientation()` 方法和 `Camera.Parameters.setRotation()` 方法。
首先,在 `SurfaceView` 上设置 `setCameraDisplayOrientation()` 方法:
```java
private void setCameraDisplayOrientation(Context context, int cameraId, Camera camera) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
int rotation = ((Activity) context).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; // mirror the image
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
```
然后,在 `SurfaceView` 中设置 `setPreviewCallback()` 方法:
```java
mCamera.setPreviewCallback(new Camera.PreviewCallback() {
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
// flip the image horizontally (mirror)
for (int i = 0; i < data.length / 2; i += 2) {
byte temp = data[i];
data[i] = data[data.length - i - 2];
data[data.length - i - 2] = temp;
}
}
});
```
这样就可以实现 Android 相机预览的镜像效果了。
阅读全文