zl程序教程

您现在的位置是:首页 >  Java

当前栏目

从零开发一款相机APP 第十篇:Camera2 zoom变焦

2023-02-18 16:35:35 时间
本课程内容由 @公众号:小驰笔记出品,欢迎关注公众号,获取更多交流信息~
欢迎访问个人博客:www.xiaochibiji.com

关于数码变焦,前面专门写过一篇文章:

https://mp.weixin.qq.com/s/XZzQytKVz-F0sUMW61FFRQ

一、获取支持的最大数码变焦倍数

CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM

二、请求裁剪范围

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相关软件开发工作,

公众号记录生活和工作的点滴,