I am using camera 2. I want to customize the surface view height and width. I am using the following code.
<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 Code:
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();
}
}
I want to show only 400dp of the surface view. But the whole height is shrinked and displaying in the surface view.
But I am getting following OP:
How to show only 400dp of camera view in the surface view.
I tried the Soution. But I am not getting the expected result.
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);
}
I am getting the following result.
I gave 200 width and 200 height. But not getting expected result. And also camera view also getting stretched.