使用Objective-C放大和缩小相机视图?

时间:2016-03-07 10:31:15

标签: ios camera zoom uipinchgesturerecognizer

如何应用放大和缩小相机视图使用UIPinchGestureRecognizer和AVCaptureDevice。 它没有正确缩放。
缩小功能在以下代码中不起作用:

 AVCaptureDevice *device =[AVCaptureDevice defaultDeviceWithMediaType:
                                                       AVMediaTypeVideo];
 AVCaptureDeviceFormat *format = device.activeFormat;
 CGFloat maxZoomFactor = format.videoMaxZoomFactor;
 const CGFloat pinchVelocityDividerFactor = 2.0f;

 if (pinchRecognizer.state == UIGestureRecognizerStateChanged || pinchRecognizer.state ==UIGestureRecognizerStateBegan)
 {
     NSError *error = nil;
      if ([device lockForConfiguration:&error])
      {
         CGFloat desiredZoomFactor = device.videoZoomFactor +
             atan2f(pinchRecognizer.velocity, pinchVelocityDividerFactor);

          // Check if desiredZoomFactor fits required range from 1.0
                                   //to activeFormat.videoMaxZoomFactor
          if((1.0 <= pinchRecognizer.scale) && (2.5 >= pinchRecognizer.scale))
          device.videoZoomFactor = pinchRecognizer.scale * pinchRecognizer.scale;  

        [device unlockForConfiguration];
      }
      else
      {
        NSLog(@"error: %@", error);
      }
 }  
}

请帮助任何人。
感谢

1 个答案:

答案 0 :(得分:3)

// PinchGesture识别器方法定义

- (void)handlePinchZoom:(UIPinchGestureRecognizer *)pinchRecognizer
 {
     AVCaptureDevice *device =[AVCaptureDevicedefaultDeviceWithMediaType:
                                                       AVMediaTypeVideo];
     AVCaptureDeviceFormat *format = device.activeFormat;
     CGFloat maxZoomFactor = format.videoMaxZoomFactor;
     NSArray *formats = device.formats;
     const CGFloat pinchVelocityDividerFactor = 2.0f;
     if (pinchRecognizer.state == UIGestureRecognizerStateChanged || pinchRecognizer.state ==UIGestureRecognizerStateBegan)
     {
        NSError *error = nil;
        if ([device lockForConfiguration:&error])
        {
           CGFloat desiredZoomFactor = device.videoZoomFactor +
           atan2f(pinchRecognizer.velocity, pinchVelocityDividerFactor);

           device.videoZoomFactor =   MAX(1.0, MIN(desiredZoomFactor,
                                          device.activeFormat.videoMaxZoomFactor));
           [device unlockForConfiguration];
        } 
       else
       {
         NSLog(@"error: %@", error);
       }
     }
  }