ios 通过代码调整焦距

        我们在自定义相机时,若要实现镜头变焦,也就是推近或者拉远焦距,iOS 7以后的实现:可以通过修改AVCaptureDevice的 方法rampToVideoZoomFactor withRate 来实现镜头变焦,带有动画(本质上是修改AVCaptureDevice的缩放系数videoZoomFactor),代码如下(通过手势缩放):

//最小缩放值
- (CGFloat)minZoomFactor
{
    CGFloat minZoomFactor = 1.0;
    if (@available(iOS 11.0, *)) {
        minZoomFactor = self.device.minAvailableVideoZoomFactor;
    }
    return minZoomFactor;
}

//最大缩放值
- (CGFloat)maxZoomFactor
{
    CGFloat maxZoomFactor = self.device.activeFormat.videoMaxZoomFactor;
    if (@available(iOS 11.0, *)) {
        maxZoomFactor = self.device.maxAvailableVideoZoomFactor;
    }
    
    if (maxZoomFactor > 6.0) {
        maxZoomFactor = 6.0;
    }
    return maxZoomFactor;
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    if ([gestureRecognizer isKindOfClass:[UIPinchGestureRecognizer class]]){
        self.currentZoomFactor = self.device.videoZoomFactor;
    }
    return YES;
}
//缩放手势
- (void)zoomChangePinchGestureRecognizerClick:(UIPinchGestureRecognizer *)pinchGestureRecognizer
{
    if (pinchGestureRecognizer.state == UIGestureRecognizerStateBegan ||
        pinchGestureRecognizer.state == UIGestureRecognizerStateChanged)
    {
        CGFloat currentZoomFactor = self.currentZoomFactor * pinchGestureRecognizer.scale;
        
        [self changeFactor:currentZoomFactor];
    }
    else
    {
    }
}
-(void) changeFactor:(CGFloat)currentZoomFactor{
    if (currentZoomFactor < self.maxZoomFactor &&
        currentZoomFactor > self.minZoomFactor){
        
        NSError *error = nil;
        if ([self.device lockForConfiguration:&error] ) {
//            dispatch_async(dispatch_get_main_queue(), ^{
                [self.device rampToVideoZoomFactor:currentZoomFactor withRate:3];//rate越大,动画越慢
//                self.device.videoZoomFactor = currentZoomFactor;//无动画
                [self.device unlockForConfiguration];
//            });

        }
        else {
            QRLog( @"Could not lock device for configuration: %@", error );
        }
    }
}

UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(zoomChangePinchGestureRecognizerClick:)];
    pinchGesture.delegate = self;
    [self.view addGestureRecognizer:pinchGesture];
    self.currentZoomFactor = 1;

总之:缩放只用到了系统的API             [self.device rampToVideoZoomFactor:currentZoomFactor withRate:3];//rate越大动画越慢

之前版本缩放还可以通过AVCaptureConnection,这里不做介绍了。

参考对象:苏沫离  https://www.jianshu.com/p/3f9b2b0ab8d4

 

你可能感兴趣的:(Xcode)