Write in front:

This article mainly introduces the Camera2 API, if the camera lens zoom, here said zoom specified digital zoom.

As shown below, the normal screen is on the left and the zoom screen is on the right. Next, let’s take a look at how this works in code.

First, let’s take a look at the relevant interfaces that Google provides for us

1, get the support of digital zoom multiples CameraCharacteristics. The biggest SCALER_AVAILABLE_MAX_DIGITAL_ZOOM

SCALER_CROP_REGION CaptureRequest.SCALER_CROP_REGION

As can be seen from the interface above, we need to zoom in and out the lens, which must know the maximum digital zoom multiple supported by the device, which determines the range of adjustment we can make. The principle of digital zoom is to cut data, so we need to set the region rectangle that the image needs to display. This Google also provides us with the corresponding request interface CaptureRequest.SCALER_CROP_REGION.

Second, let’s look at the implementation of the code:

@param zoom zoom (0~1.0) **/ public void applyZoom(float zoom) {float old = mZoomValue; mZoomValue = zoom; if(mCameraCharacteristics ! = null){ float maxZoom = mCameraCharacteristics.get( CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM); // Converting 0.0F-1.0f zoom scale to the actual camera digital zoom scale // (which will be for example, 1.0-10.0) float calculatedZoom = (mZoomValue * (maxZoom - 1.0f)) + 1.0f; Rect newRect = getZoomRect(calculatedZoom, maxZoom); mPreviewBuilder.set(CaptureRequest.SCALER_CROP_REGION, newRect); mPreviewSession.setRepeatingRequest(mPreviewBuilder.build(), null, mBackgroundHandler); Private Rect getZoomRect(float zoomLevel, float maxDigitalZoom) {Rect activeRect = new Rect(); activeRect = mCameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE); int minW = (int) (activeRect.width() / maxDigitalZoom); int minH = (int) (activeRect.height() / maxDigitalZoom); int difW = activeRect.width() - minW; int difH = activeRect.height() - minH; // When zoom is 1, we want to return new Rect(0, 0, width, height). // When zoom is maxZoom, we want to return a centered rect with minW and minH int cropW = (int) (difW * (zoomLevel - 1) / (maxDigitalZoom - 1) / 2F); int cropH = (int) (difH * (zoomLevel - 1) / (maxDigitalZoom - 1) / 2F); return new Rect(cropW, cropH, activeRect.width() - cropW, activeRect.height() - cropH); }Copy the code

I have been engaged in Android Camera related development for 5 years

Now I work in Shenzhen

Welcome to follow my wechat official account “Xiaochi Notes”.

We learn and communicate together

— — — — — — — — — — 2020.10.23