IOS AV Foundation QR code scanning zoom camera
In the last section, we add the zoom control function for the camera through gestures for the program.
Add instance variables and initialize them at the end of the viewDidLoad method:
CGFloat _initialPinchZoom;
[_previewView addGestureRecognizer:[[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchDetected:)]];
Implementation of pinchDetected: method:
- (void)pinchDetected:(UIPinchGestureRecognizer*)recogniser{ // 1 if (!_videoDevice) return; // 2 if (recogniser.state == UIGestureRecognizerStateBegan) { _initialPinchZoom = _videoDevice.videoZoomFactor; } // 3 NSError *error = nil; [_videoDevice lockForConfiguration:&error]; if (!error) { CGFloat zoomFactor; CGFloat scale = recogniser.scale; if (scale < 1.0f) { // 4 zoomFactor = _initialPinchZoom - pow(_videoDevice.activeFormat.videoMaxZoomFactor, 1.0f - recogniser.scale); } else { // 5 zoomFactor = _initialPinchZoom + pow(_videoDevice.activeFormat.videoMaxZoomFactor, (recogniser.scale - 1.0f) / 2.0f); } // 6 zoomFactor = MIN(10.0f, zoomFactor); zoomFactor = MAX(1.0f, zoomFactor); // 7 _videoDevice.videoZoomFactor = zoomFactor; // 8 [_videoDevice unlockForConfiguration]; }}
Check whether there are available video devices. Initial scaling factor is recorded at the beginning of gesture recognition. Before you modify the video device parameters, lock the video device. If the lock succeeds and the gesture behavior is calculated, scale less than 1.0 indicates that the distance between the two fingers is narrowing, and the program needs to zoom in on the camera. If the scale is greater than 1.0, the distance between the two fingers is increasing, and the program needs to narrow down the camera. The formula in steps 4th and 5th is used to make scaling look more natural. Limit the maximum and minimum scaling values. Set a scaling factor for the video device. Finally, unlock the video device.
Compile and execute. The scaling effect on the mobile phone is as follows: