2
votes

I am doing a project with my camera by using AVFoundation/AVFoundation.h. Now, I want to achieve zooming the screen.

I checked the document on AVCaptureDevice, and found a parameter named "videoZoomFactor", which said it can be used for defining the zoom rates.

Therefore, I used the following code:

device.videoZoomFactor = device.activeFormat.videoZoomFactorUpscaleThreshold;

But the app crashed and showed 「the videoZoomFactor is out of range.」 How did this happen? What should I do to zoom the camera?

3

3 Answers

3
votes

It works correctly for me, in the following snippet:

if ([device respondsToSelector:@selector(setVideoZoomFactor:)]) {
    if ([ device lockForConfiguration:nil]) {
        float zoomFactor = device.activeFormat.videoZoomFactorUpscaleThreshold;
        [device setVideoZoomFactor:zoomFactor];
        [device unlockForConfiguration];
    }
}

Try logging device.activeFormat.videoZoomFactorUpscaleThreshold and seeing what the value actually is.

0
votes

You need to check sessionPreset first, using - (BOOL)supportsAVCaptureSessionPreset:(NSString *)preset

also device.videoZoomFactor range should between 1.0 and 2.0 so check the range first before do the setting.

0
votes
// in class
CGFloat zoomBegin;
CGFloat zoomMax;

// on create video connection
NSError *error;
if( YES == [camDevice lockForConfiguration:&error] )
{
    // A maximum zoom factor of 1 indicates no zoom is available.
    zoomMax = camDevice.activeFormat.videoMaxZoomFactor;
    [camDevice unlockForConfiguration];
}
[self.view addGestureRecognizer:[[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchToZoom:)]];

- (void)pinchToZoom:(UIPinchGestureRecognizer*)gesture
{
    switch (gesture.state)
    {
        case UIGestureRecognizerStateBegan:
        {
            zoomBegin = camDevice.videoZoomFactor;
            NSLog(@"zoom begin:%.3f", zoomBegin);
        }break;
        case UIGestureRecognizerStateChanged:
        {
            CGFloat zoomTo = zoomBegin + (gesture.scale * 2 - 2);
            // step 0.01 between 1.0 and zoomMax (4x on iPhone 6s)
            int msc = (int)(((zoomTo+0.001)*100))%100;
            zoomTo = (NSInteger)zoomTo + msc * 0.01;
            zoomTo = fmaxf(1, fminf(zoomTo, zoomMax));

            if ( camDevice.videoZoomFactor != zoomTo )
            {
                dispatch_async(sessionQueue, ^{
                    NSError *error;
                    if ( YES == [camDevice lockForConfiguration:&error] )
                    {
                        camDevice.videoZoomFactor = zoomTo;
                        [camDevice unlockForConfiguration];
                        NSLog(@"zoom changed:%.3f", zoomTo);
                    }
                });
            }
        }break;
        default:
            break;
    }
}