iOS扫描二维码实现手势拉近拉远镜头
在做扫码需求,往往会有放大镜头需求。
苹果提供了AVCaptureConnection中,videoScaleAndCropFactor:缩放裁剪系数,使用该属性,可以实现拉近拉远镜头。再结合手势UIPinchGestureRecognizer,就很简单实现手势拉近拉远镜头。
手势代码
///记录开始的缩放比例
@property(nonatomic,assign)CGFloatbeginGestureScale;
///最后的缩放比例
@property(nonatomic,assign)CGFloateffectiveScale;
-(void)cameraInitOver
{
if(self.isVideoZoom){
UIPinchGestureRecognizer*pinch=[[UIPinchGestureRecognizeralloc]initWithTarget:selfaction:@selector(pinchDetected:)];
pinch.delegate=self;
[self.viewaddGestureRecognizer:pinch];
}
}
-(void)pinchDetected:(UIPinchGestureRecognizer*)recogniser
{
self.effectiveScale=self.beginGestureScale*recogniser.scale;
if(self.effectiveScale<1.0){
self.effectiveScale=1.0;
}
[self.scanObjsetVideoScale:self.effectiveScale];
}
-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer*)gestureRecognizer
{
if([gestureRecognizerisKindOfClass:[UIPinchGestureRecognizerclass]]){
_beginGestureScale=_effectiveScale;
}
returnYES;
}
拉近拉远镜头代码
-(void)setVideoScale:(CGFloat)scale
{
[_input.devicelockForConfiguration:nil];
AVCaptureConnection*videoConnection=[selfconnectionWithMediaType:AVMediaTypeVideofromConnections:[[selfstillImageOutput]connections]];
CGFloatmaxScaleAndCropFactor=([[self.stillImageOutputconnectionWithMediaType:AVMediaTypeVideo]videoMaxScaleAndCropFactor])/16;
if(scale>maxScaleAndCropFactor)
scale=maxScaleAndCropFactor;
CGFloatzoom=scale/videoConnection.videoScaleAndCropFactor;
videoConnection.videoScaleAndCropFactor=scale;
[_input.deviceunlockForConfiguration];
CGAffineTransformtransform=_videoPreView.transform;
[CATransactionbegin];
[CATransactionsetAnimationDuration:.025];
_videoPreView.transform=CGAffineTransformScale(transform,zoom,zoom);
[CATransactioncommit];
}
有一点需要注意:thevideoScaleAndCropFactorpropertymaybesettoavalueintherangeof1.0tovideoMaxScaleAndCropFactor,videoScaleAndCropFactor这个属性取值范围是1.0-videoMaxScaleAndCropFactor,如果你设置超出范围会崩溃哦!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。