写在后面:

这篇文章次要介绍Camera2 API上,如果进行相机镜头的缩放,这里说的缩放指定的数码变焦。

如下图所示,右边是失常状况下的画面,右侧是镜头拉近的画面,接下来,咱们就看下代码上是如何实现的。

一、 咱们先来看下Google为咱们提供了哪些相干的接口

1、获取反对的最大数码变焦倍数
CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM

2、申请裁剪范畴
CaptureRequest.SCALER_CROP_REGION,

从下面的接口咱们也能够看的进去,咱们须要进行镜头缩放,那必定得晓得设施反对的最大数码变焦倍数,这个决定了咱们能够调节的范畴。数码变焦的原理,就是对数据进行了裁剪,那咱们就须要设置图像须要显示的区域矩形,这个Google也为咱们提供了绝对应的申请接口CaptureRequest.SCALER_CROP_REGION。

二、接下来看下代码上的具体实现:

/** * 进行镜头缩放 * @param 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);}

自己从事Android Camera相干开发已有5年

目前在深圳下班

欢送大家关注我的微信公众号“小驰笔记”

大家一起学习交换

---------- 2020.10.23