Camera2 TextureView预览摄像头角度
时间: 2023-09-13 13:03:50 浏览: 188
Android Camera2 实现预览功能
要预览摄像头角度,可以通过设置TextureView的transform matrix来实现。首先,需要获取当前设备方向和相机传感器方向的差异,可以使用以下代码:
```java
int sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
int deviceOrientation = getWindowManager().getDefaultDisplay().getRotation();
int surfaceRotation = ORIENTATIONS.get(deviceOrientation);
int rotation = (sensorOrientation - surfaceRotation + 360) % 360;
```
其中,characteristics是当前相机设备的CameraCharacteristics实例,ORIENTATIONS是一个常量数组,包含了设备方向和Surface方向之间的映射关系。
接下来,根据计算出的rotation值,设置TextureView的transform matrix:
```java
Matrix matrix = new Matrix();
RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
RectF bufferRect = new RectF(0, 0, previewSize.getHeight(), previewSize.getWidth());
float centerX = viewRect.centerX();
float centerY = viewRect.centerY();
if (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) {
bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
float scale = Math.max(
(float) viewHeight / previewSize.getHeight(),
(float) viewWidth / previewSize.getWidth());
matrix.postScale(scale, scale, centerX, centerY);
matrix.postRotate(90 * (rotation - 2), centerX, centerY);
} else if (rotation == Surface.ROTATION_180) {
matrix.postRotate(180, centerX, centerY);
}
textureView.setTransform(matrix);
```
上述代码中,viewWidth和viewHeight分别是TextureView的宽高,previewSize是预览尺寸。根据当前方向的不同,使用不同的变换方式设置transform matrix。最后,将变换矩阵应用到TextureView上即可。
阅读全文