欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-08-17 20:54:55
在做扫码需求,往往会有放大镜头需求。 苹果提供了avcaptureconnection中,videoscaleandcropfactor:缩放裁剪系数,使用该属性,...

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

苹果提供了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,如果你设置超出范围会崩溃哦!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。