AVCaptureDevice相机变焦 [英] AVCaptureDevice Camera Zoom

查看:353
本文介绍了AVCaptureDevice相机变焦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的AVCaptureSession,可以在我的应用中获取相机并拍照。如何使用相机的 UIGestureRecognizer 实现缩放到缩放功能?

I have a simple AVCaptureSession running to get a camera feed in my app and take photos. How can I implement the 'pinch to zoom' functionality using a UIGestureRecognizer for the camera?

推荐答案

接受的答案实际上是过时的,我不确定它是否会实际拍摄放大图像的照片。有一种放大方法,如bcattle的回答说。他回答的问题是它没有掌握用户可以放大然后从该变焦位置重新启动的事实。他的解决方案会创造一些不太优雅的跳跃。

The accepted answer is actually outdated and I'm not sure it will actually take the photo of the zoomed in image. There is a method to zoom in like bcattle answer says. The problem of his answer is that it does not take in charge the fact that the user can zoom in and then restart from that zoom position. His solution will create some kind of jumps that are not really elegant.

最简单,最优雅的方法是使用捏合手势的速度。

The easiest and most elegant way of doing this is to use the velocity of the pinch gesture.

-(void) handlePinchToZoomRecognizer:(UIPinchGestureRecognizer*)pinchRecognizer {
    const CGFloat pinchVelocityDividerFactor = 5.0f;

    if (pinchRecognizer.state == UIGestureRecognizerStateChanged) {
        NSError *error = nil;
        if ([videoDevice lockForConfiguration:&error]) {
            CGFloat desiredZoomFactor = device.videoZoomFactor + atan2f(pinchRecognizer.velocity, pinchVelocityDividerFactor);
            // Check if desiredZoomFactor fits required range from 1.0 to activeFormat.videoMaxZoomFactor
            device.videoZoomFactor = MAX(1.0, MIN(desiredZoomFactor, device.activeFormat.videoMaxZoomFactor));
            [videoDevice unlockForConfiguration];
        } else {
            NSLog(@"error: %@", error);
        }
    }
}

我发现添加了arctan功能到速度会轻松放大缩小效果。它并不完美,但效果足以满足需求。当它几乎达到1时,可能还有另一个功能可以轻松缩小。

I found that adding the arctan function to the velocity will ease the zoom in zoom out effect a bit. It is not exactly perfect but the effect is good enough for the needs. There could probably be another function to ease the zoom out when it almost reaches 1.

注意:此外,捏合手势的比例变为从0到无穷大,0到1被捏入(缩小),1到无限被捏出(放大)。要想有一个很好的放大缩小效果,你需要有一个数学方程式。 Velocity实际上是从无限到无限,0是起点。

NOTE: Also, the scale of a pinch gesture goes from 0 to infinite with 0 to 1 being pinching in (zoom out) and 1 to infinite being pinching out (zoom in). To get a good zoom in zoom out effect with this you'd need to have a math equation. Velocity is actually from -infinite to infinite with 0 being the starting point.

编辑:修复了范围异常的崩溃。感谢 @garafajon

EDIT: Fixed crash on range exception. Thanks to @garafajon!

这篇关于AVCaptureDevice相机变焦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆