我正在使用相机 2。我想自定义表面视图的高度和宽度。
我正在使用以下代码。
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/holo_blue_dark">
<TextureView
android:id="@+id/texture"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
Java代码:
protected void createCameraPreview() {
try {
SurfaceTexture texture = textureView.getSurfaceTexture();
assert texture != null;
texture.setDefaultBufferSize(imageDimension.getWidth(), imageDimension.getHeight());
Surface surface = new Surface(texture);
captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequestBuilder.addTarget(surface);
cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback(){
@Override
public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
//The camera is already closed
if (null == cameraDevice) {
return;
}
// When the session is ready, we start displaying the preview.
cameraCaptureSessions = cameraCaptureSession;
updatePreview();
}
@Override
public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
Toast.makeText(MainActivity.this, "Configuration change", Toast.LENGTH_SHORT).show();
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
我只想显示 400dp 的表面视图。但整个高度被缩小并显示在表面视图中。
Expected OP:
![enter image description here](https://i.stack.imgur.com/hpYif.png)
但我收到以下OP:
如何在表面视图中仅显示 400dp 的相机视图。
我尝试过Soution https://stackoverflow.com/a/21630665/2845346。但我没有得到预期的结果。
private void updateTextureMatrix(int width, int height) { // 200, 200
int previewWidth = getScreenWidth(); //720
int previewHeight = getScreenHeight(); // 1280
float ratioSurface = (float) width / height; // 1.0
float ratioPreview = (float) previewWidth / previewHeight; // 0.5625
float scaleX; float scaleY;
if (ratioSurface > ratioPreview) { //(0.5625 > 1.0)
scaleX = (float) height / previewHeight; // 0.15625
scaleY = 1;
} else {
scaleX = 1;
scaleY = (float) width / previewWidth;
}
Matrix matrix = new Matrix();
matrix.setScale(scaleX, scaleY); //(0.15625 , 1.0)
textureView.setTransform(matrix);
float scaledWidth = width * scaleX; // 31.25
float scaledHeight = height * scaleY; // 200.0
float dx = (width - scaledWidth) / 2; // 84.375
float dy = (height - scaledHeight) / 2; // 0.00
textureView.setTranslationX(dx);
textureView.setTranslationY(dy);
}
我得到以下结果。
我给了200宽度和200高度。但没有得到预期的结果。而且相机视野也被拉伸。