实现焦距调节
声明两个属性,遵循手势的协议<UIGestureRecognizerDelegate>
/*** 记录开始的缩放比例*/@property(nonatomic,assign)CGFloat beginGestureScale;/*** 最后的缩放比例*/@property(nonatomic,assign)CGFloat effectiveScale;
这两个属性分别用于记录缩放的比例。相机支持的焦距是1.0~67.5,所以再控制器加载的时候分别给这两个属性附上一个初值 1.0。
之后给view添加一个缩放手势,手势调用的方法如下
//缩放手势 用于调整焦距
- (void)handlePinchGesture:(UIPinchGestureRecognizer *)recognizer{BOOL allTouchesAreOnThePreviewLayer = YES;NSUInteger numTouches = [recognizer numberOfTouches], i;for ( i = 0; i < numTouches; ++i ) {CGPoint location = [recognizer locationOfTouch:i inView:self.backView];CGPoint convertedLocation = [self.previewLayer convertPoint:location fromLayer:self.previewLayer.superlayer];if ( ! [self.previewLayer containsPoint:convertedLocation] ) {allTouchesAreOnThePreviewLayer = NO;break;}
}if ( allTouchesAreOnThePreviewLayer ) {self.effectiveScale = self.beginGestureScale * recognizer.scale;if (self.effectiveScale < 1.0){self.effectiveScale = 1.0;}NSLog(@"%f-------------->%f------------recognizerScale%f",self.effectiveScale,self.beginGestureScale,recognizer.scale);CGFloat maxScaleAndCropFactor = [[self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo] videoMaxScaleAndCropFactor];NSLog(@"%f",maxScaleAndCropFactor);if (self.effectiveScale > maxScaleAndCropFactor)self.effectiveScale = maxScaleAndCropFactor;[CATransaction begin];[CATransaction setAnimationDuration:.025];[self.previewLayer setAffineTransform:CGAffineTransformMakeScale(self.effectiveScale, self.effectiveScale)];[CATransaction commit];}}
然后在实现手势的代理方法
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{if ( [gestureRecognizer isKindOfClass:[UIPinchGestureRecognizer class]] ) {self.beginGestureScale = self.effectiveScale;}return YES;
}
在每次手势开始的时候把上一次实际缩放值赋给初始缩放值,如果不这么做的话你会发现每次手势开始的时候界面都会跳来跳去的。一个简单功能的相机基本上完成了,最后一步就是之前我们在拍照的方法里写死了一个1.0,我们还需要修改一下它,,否则虽然你看到的界面焦距改变了,但是实际拍出来的照片是没有变化的。找到拍照方法里的
[stillImageConnection setVideoScaleAndCropFactor:1.0];
修改为
[stillImageConnection setVideoScaleAndCropFactor:self.effectiveScale];
更多内容请看我的高仿微信的拍照录制视频博客