I am new to Android/Java development and need some guidance from an expert.
I am trying to display a camera preview on TextureView, but the displayed preview is zoomed and not centered.
Here are some code snippets:
For the camera initialization:
protected void initializeCamera() {
if (this.context.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
Log.e(TAG, "onCreate: Camera permission not granted");
}
try {
camManager = (CameraManager) this.context.getSystemService(Context.CAMERA_SERVICE);
textureView = new AutoFitTextureView(this.context);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
params.gravity = Gravity.CENTER;
textureView.setLayoutParams(params);
textureView.setAspectRatio(cameraResolution.previewSize.getHeight(), cameraResolution.previewSize.getWidth());
} catch (Exception e) {
Log.e(TAG, "ERROR: Camera feature check failed:" + e.getMessage());
}
}
Open camera:
private void OpenCamera(String templateType) throws CameraAccessException {
///... chechinkg the permissions
...
SurfaceTexture texture = textureView.getSurfaceTexture();
assert texture != null;
texture.setDefaultBufferSize(cameraResolution.previewSize.getWidth(), cameraResolution.previewSize.getHeight());
...
imageReaderHqCapture = ImageReader.newInstance(cameraResolution.captureSize.getWidth(), cameraResolution.captureSize.getHeight(), currentHqImageFormat, numProcessedImages);
lSurfaces.add(imageReaderHqCapture.getSurface());
camManager.openCamera(camId, new CameraDevice.StateCallback() {
@Override
public void onOpened(@NonNull CameraDevice cameraDevice) {
camDevice = cameraDevice;
Log.d(TAG, "onOpened");
try {
cameraDevice.createCaptureSession(lSurfaces, new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
...
try {
configureCaptureHqBuilder(templateType, characteristics);
configureCapturePreviewBuilder(characteristics);
scheduleNextCapture(0);// start scheduler
} catch (Exception e) {
...
}
}
}, null);
} catch (Exception e) {
...
}
}
}