欢迎来到代码驿站!

iOS代码

当前位置:首页 > 移动开发 > iOS代码

iOS扫描二维码实现手势拉近拉远镜头

时间:2020-12-11 21:48:20|栏目:iOS代码|点击:

在做扫码需求,往往会有放大镜头需求。

苹果提供了AVCaptureConnection中,videoScaleAndCropFactor:缩放裁剪系数,使用该属性,可以实现拉近拉远镜头。再结合手势UIPinchGestureRecognizer,就很简单实现手势拉近拉远镜头。

手势代码

///记录开始的缩放比例
@property(nonatomic,assign)CGFloat beginGestureScale;

///最后的缩放比例
@property(nonatomic,assign)CGFloat effectiveScale;

- (void)cameraInitOver
{
 if (self.isVideoZoom) {
  UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchDetected:)];
  pinch.delegate = self;
  [self.view addGestureRecognizer:pinch];
 }
}

- (void)pinchDetected:(UIPinchGestureRecognizer*)recogniser
{
 self.effectiveScale = self.beginGestureScale * recogniser.scale;
 if (self.effectiveScale < 1.0){
  self.effectiveScale = 1.0;
 }
 [self.scanObj setVideoScale:self.effectiveScale];

}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
 if ( [gestureRecognizer isKindOfClass:[UIPinchGestureRecognizer class]] ) {
  _beginGestureScale = _effectiveScale;
 }
 return YES;
}

拉近拉远镜头代码

- (void)setVideoScale:(CGFloat)scale
{
 [_input.device lockForConfiguration:nil];

 AVCaptureConnection *videoConnection = [self connectionWithMediaType:AVMediaTypeVideo fromConnections:[[self stillImageOutput] connections]];
 CGFloat maxScaleAndCropFactor = ([[self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo] videoMaxScaleAndCropFactor])/16;

 if (scale > maxScaleAndCropFactor)
  scale = maxScaleAndCropFactor;

 CGFloat zoom = scale / videoConnection.videoScaleAndCropFactor;

 videoConnection.videoScaleAndCropFactor = scale;

 [_input.device unlockForConfiguration];

 CGAffineTransform transform = _videoPreView.transform;
 [CATransaction begin];
 [CATransaction setAnimationDuration:.025];

  _videoPreView.transform = CGAffineTransformScale(transform, zoom, zoom);

 [CATransaction commit];

}

有一点需要注意:the videoScaleAndCropFactor property may be set to a value in the range of 1.0 to videoMaxScaleAndCropFactor,videoScaleAndCropFactor这个属性取值范围是1.0-videoMaxScaleAndCropFactor,如果你设置超出范围会崩溃哦!

上一篇:iOS自动移除KVO观察者的实现方法

栏    目:iOS代码

下一篇:iOS10适配之权限Crash问题的完美解决方案

本文标题:iOS扫描二维码实现手势拉近拉远镜头

本文地址:http://www.codeinn.net/misctech/31807.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有