首先我们来想一想具体的步骤,大概流程应该是:1.打开设备的摄像头-->2.进行二维码图像捕获-->3.获取捕获的图像进行解析-->4.取得解析结果进行后续处理。这些流程需要用到AVFoundation
这个库,注意导入。
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//获取一个AVCaptureDeviceInput对象,将上面的'摄像头'作为输入设备
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:_device error:nil];
//拍完照片以后,需要一个AVCaptureMetadataOutput对象将获取的'图像'输出,以便进行对其解析
AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc]init];
//获取输出需要设置代理,在代理方法中获取
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
//设置输出类型,如AVMetadataObjectTypeQRCode是二维码类型,下面还增加了条形码。如果扫描的是条形码也能识别
output.metadataObjectTypes = @[AVMetadataObjectTypeEAN13Code,
AVMetadataObjectTypeEAN8Code,
AVMetadataObjectTypeCode128Code,
AVMetadataObjectTypeQRCode];
//设置扫描区域
// Y <------------------+ 坐标轴
// |
// |
// |
// |
// |
// |
// |
// V
// X
//设置要点 x和y互换 H和W互换
CGFloat leadSpace = (kScreenWidth - MiddleWidth)/ 2;
[_output setRectOfInterest:CGRectMake(0.2, leadSpace / kScreenWidth ,0.8 * kScreenWidth / kScreenHeight, 0.8)];
上面完成了捕获的设置,但是并未正在开始'扫描',要完成一次扫描的过程,需要用到AVCaptureSession
这个类,这个session类把一次扫描看做一次会话,会话开始后才是正在的'扫描'开始,具体代码如下。
AVCaptureSession *session = [[AVCaptureSession alloc]init];
[session setSessionPreset:AVCaptureSessionPresetHigh];//扫描的质量
if ([session canAddInput:input]){
[session addInput:input];//将输入添加到会话中
}
if ([session canAddOutput:output]){
[session addOutput:output];//将输出添加到会话中
}
接下来我们要做的不是立即开始会话(开始扫描),如果你现在调用会话的startRunning方法的话,你会发现屏幕是一片黑,这时由于我们还没有设置相机的取景器的大小。设置取景器需要用到AVCaptureVideoPreviewLayer
这个类。具体代码如下:
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
[self.session stopRunning];//停止会话
if (metadataObjects.count > 0) {
AVMetadataMachineReadableCodeObject *obj = metadataObjects[0];
NSString *result = obj.stringValue;//这就是扫描的结果啦
//对结果进行处理...
}
}
加入照明功能能让用户在光照条件不好的情况下顺利的进行进行扫描操作,代码如下:
////设置闪光灯
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSError *error;
if (_device.hasTorch) { // 判断设备是否有闪光灯
BOOL b = [_device lockForConfiguration:&error];
if (!b) {
if (error) {
NSLog(@"lock torch configuration error:%@", error.localizedDescription);
}
return;
}
_device.torchMode = (_device.torchMode == AVCaptureTorchModeOff ? AVCaptureTorchModeOn : AVCaptureTorchModeOff);
[_device unlockForConfiguration];
}
}
从图片中直接读取二维码的功能在iOS7上面苹果没有实现,不过在iOS上已经填补了这一功能。主要用到的是读取主要用到CoreImage。
//获取图片中的二维码信息
- (NSString *)scQRReaderForImage:(UIImage *)qrimage{
CIContext *context = [CIContext contextWithOptions:nil];
CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:context options:@{CIDetectorAccuracy:CIDetectorAccuracyHigh}];
CIImage *image = [CIImage imageWithCGImage:qrimage.CGImage];
NSArray *features = [detector featuresInImage:image];
CIQRCodeFeature *feature = [features firstObject];
NSString *result = feature.messageString;
return result;
}
生成二维码和从图片中读取二维码一样要用到CoreImage,具体步骤如下:
- (UIImage *)makeQRCodeForString:(NSString *)string{
NSString *text = string;
NSData *stringData = [text dataUsingEncoding: NSUTF8StringEncoding];
//生成
CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
[qrFilter setValue:stringData forKey:@"inputMessage"];//通过kvo方式给一个字符串,生成二维码
[qrFilter setValue:@"M" forKey:@"inputCorrectionLevel"];//设置二维码的纠错水平,越高纠错水平越高,可以污损的范围越大 L:7% M:15% Q:25% H:30%
//二维码颜色
UIColor *onColor = [UIColor redColor];
UIColor *offColor = [UIColor blueColor];
//上色,如果只要白底黑块的QRCode可以跳过这一步
CIFilter *colorFilter = [CIFilter filterWithName:@"CIFalseColor"
keysAndValues:
@"inputImage",qrFilter.outputImage,
@"inputColor0",[CIColor colorWithCGColor:onColor.CGColor],
@"inputColor1",[CIColor colorWithCGColor:offColor.CGColor],
nil];
CIImage *qrImage = colorFilter.outputImage;//拿到二维码图片
//放大更清楚
qrImage = [qrImage imageByApplyingTransform:CGAffineTransformMakeScale(20, 20)];
NSLog(@"%@",qrImage);
//绘制
CGSize size = [[UIImage imageWithCIImage:qrImage] size];
CGImageRef cgImage = [[CIContext contextWithOptions:nil] createCGImage:qrImage fromRect:qrImage.extent];
UIGraphicsBeginImageContext(size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetInterpolationQuality(context, kCGInterpolationNone);
CGContextScaleCTM(context, 1.0, -1.0);//生成的QRCode就是上下颠倒的,需要翻转一下
CGContextDrawImage(context, CGContextGetClipBoundingBox(context), cgImage);
UIImage *codeImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRelease(cgImage);
return codeImage;
}
对图片添加水印
- (UIImage *)addImageToSuperImage:(UIImage *)superImage withSubImage:(UIImage *)subImage andSubImagePosition:(CGRect)posRect{
UIGraphicsBeginImageContext(superImage.size);
[superImage drawInRect:CGRectMake(0, 0, superImage.size.width, superImage.size.height)];
//四个参数为水印图片的位置
[subImage drawInRect:posRect];
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultingImage;
}