Android Camera开发入门 第十篇:Camera2 zoom变焦

【小驰笔记】【Android Camera开发】【Android Camera2】【camera2】

本课程内容由 @小驰笔记 出品,欢迎关注,获取更多交流信息~
欢迎访问个人博客: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);
        returnnew Rect(cropW, cropH, activeRect.width() - cropW,
                activeRect.height() - cropH);
}

推荐阅读:

关于我

博客大更新_

今年,做好一件事情

一篇文章带你了解Android 最新Camera框架

深圳上班,

从事Android Camera相关软件开发工作,

记录生活和工作的点滴,

点击关注“小驰笔记”,期待和你相遇~

posted @ 2022-09-01 22:58  小驰行动派  阅读(154)  评论(0编辑  收藏  举报  来源