camera2横屏预览
时间: 2023-07-28 12:07:35 浏览: 54
如果需要在横屏模式下进行 Camera2 预览,可以通过以下步骤实现:
1. 在 AndroidManifest.xml 文件中,为相应的 Activity 添加如下属性:
```
android:screenOrientation="landscape"
```
2. 在布局文件中,将 TextureView 或 SurfaceView 设置为横向铺满整个屏幕,可以使用以下代码:
```
<TextureView
android:id="@+id/texture_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
或
```
<SurfaceView
android:id="@+id/surface_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
3. 在代码中,创建一个全屏的 CaptureRequest.Builder 对象,可以使用以下代码:
```
int rotation = getWindowManager().getDefaultDisplay().getRotation();
int sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
int displayRotation = (rotation - sensorOrientation + 360) % 360;
int width = textureView.getWidth();
int height = textureView.getHeight();
Rect rect = new Rect(0, 0, width, height);
RectF rectF = new RectF(rect);
Matrix matrix = new Matrix();
matrix.setRectToRect(rectF, rectF, Matrix.ScaleToFit.FILL);
matrix.postRotate(displayRotation, width / 2f, height / 2f);
matrix.invert(matrix);
RectF mappedRectF = new RectF();
matrix.mapRect(mappedRectF, rectF);
CaptureRequest.Builder builder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
builder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
builder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
builder.set(CaptureRequest.SCALER_CROP_REGION, mappedRectF);
builder.addTarget(surface);
```
其中,characteristics 为相机的特性,可以通过 CameraManager.getCameraCharacteristics() 方法获取;surface 为输出 Surface,可以通过 TextureView 或 SurfaceView 的 getSurface() 方法获取。
4. 创建一个全屏的 CaptureRequest 对象,并设置到 CameraCaptureSession 中,可以使用以下代码:
```
cameraDevice.createCaptureSession(Collections.singletonList(surface), new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(@NonNull CameraCaptureSession session) {
try {
session.setRepeatingRequest(builder.build(), null, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onConfigureFailed(@NonNull CameraCaptureSession session) {
}
}, null);
```
这样就可以在横屏模式下实现 Camera2 的全屏预览了。