二维码扫描之rectOfInterest

设置扫描范围

在AVCaptureMetadataOutput中有一个叫做rectOfInterest的CGRect类型属性。

/*!
 @property rectOfInterest
 @abstract
    Specifies a rectangle of interest for limiting the search area for visual metadata.
 
 @discussion
    The value of this property is a CGRect that determines the receiver's rectangle of interest for each frame of video. The rectangle's origin is top left and is relative to the coordinate space of the device providing the metadata. Specifying a rectOfInterest may improve detection performance for certain types of metadata. The default value of this property is the value CGRectMake(0, 0, 1, 1). Metadata objects whose bounds do not intersect with the rectOfInterest will not be returned.
 */
@property(nonatomic) CGRect rectOfInterest NS_AVAILABLE_IOS(7_0);

这个属性用来限制扫描范围。
这个属性的每一个值代表的是对应轴上的比例大小。
设置的时候当做是横屏来写就可以了。

获取rectOfInterest

//readerViewBounds为屏幕大小,rect为扫描view的frame
-(CGRect)getScanCrop:(CGRect)rect readerViewBounds:(CGRect)readerViewBounds {
    CGFloat x,y,width,height;
    x = (CGRectGetHeight(readerViewBounds)-CGRectGetHeight(rect))/2/CGRectGetHeight(readerViewBounds);
    y = (CGRectGetWidth(readerViewBounds)-CGRectGetWidth(rect))/2/CGRectGetWidth(readerViewBounds);
    width = CGRectGetHeight(rect)/CGRectGetHeight(readerViewBounds);
    height = CGRectGetWidth(rect)/CGRectGetWidth(readerViewBounds);
    return CGRectMake(x, y, width, height);
}

缩放

需要两个全局变量

    AVCaptureDevice * currentdevice; //获取摄像设备
    CGFloat _initialPinchZoom; //缩放系数

添加Pinch手势
Pinch手势响应

- (void)pinchDetected:(UIPinchGestureRecognizer*)recogniser {
//检查是否有可用的视频设备
    if (!currentdevice) {
        return;
    }
// 在手势识别开始时,记录初始缩放系数。
    if (recogniser.state == UIGestureRecognizerStateBegan) {
        _initialPinchZoom = currentdevice.videoZoomFactor;
    }
//在开始修改视频设备参数前,锁定视频设备。锁定成功后,计算缩放系数(设置缩放范围)。
    NSError *error = nil;
    [currentdevice lockForConfiguration:&error];
    if (!error) {
        CGFloat zoomFactor;
        CGFloat scale = recogniser.scale;
        if (scale < 1.0f) {
            zoomFactor = _initialPinchZoom - pow(currentdevice.activeFormat.videoMaxZoomFactor, 1.0f - recogniser.scale);
        } else {
            zoomFactor = _initialPinchZoom + pow(currentdevice.activeFormat.videoMaxZoomFactor, (recogniser.scale - 1.0f) / 2.0f);
        }
        zoomFactor = MIN(10.0f, zoomFactor);
        zoomFactor = MAX(1.0f, zoomFactor);
        currentdevice.videoZoomFactor = zoomFactor;
// 解锁视频设备
        [currentdevice unlockForConfiguration];
    }
}

你可能感兴趣的:(二维码扫描之rectOfInterest)