这篇文章主要介绍Camera2 API上,如何进行相机镜头的缩放(这里说的缩放指的是数码变焦)。
如下图所示,第一张是正常情况下的画面,第二张是镜头拉近的画面,接下来,我们就看下代码上是如何实现的。
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);
}
好了,就介绍到这里了~,各位代码撸起来吧。
(ps:大家有想了解哪些知识点、内容(工作生活都可以),欢迎留言,我会尽力更新大家关注的方面)
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有