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.10.23


*本人從事Android Camera相關開發已有5年,
*目前在深圳上班,
*小伙伴記得點我頭像,看【個人介紹】進行關注哦,希望和更多的小伙伴一起交流 ~

=======================================================================

*本人從事Android Camera相關開發已有5年,
*目前在深圳上班,
*小伙伴記得點我頭像關注,也可以關注我的微信公眾號【小馳筆記】,希望和更多的小伙伴一起交流 ~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM