Android Camera开发系列:预览镜头缩放(数码变焦)

 写在前面:

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

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

    

                  (正常情况)                                                               (4倍数码变焦)

     

 一、 我们先来看下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);
}
    
   

------- 2020.03.19   

欢迎关注我的个人微信公众号,公众号会记录自己开发的点滴,还有日常的生活,希望和更多的小伙伴一起交流~~

(ps:本人目前在深圳上班)

猜你喜欢

转载自blog.csdn.net/Mr_ZJC/article/details/104598246