本文是查阅网上资料和demo后整理出来的, 为了日后查阅以及其他人需要只用
之前使用的是第三方库, 最近听说iOS7后, 苹果原生的二维码扫描功能效率更高, 于是学习了一下, 顺便也把生成加上.
二维码生成
- (CIImage *)createTWMForString:(NSString *)string {
CIFilter *ewmFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
// 内容
[ewmFilter setValue:[string dataUsingEncoding:NSUTF8StringEncoding] forKey:@"inputMessage"];
// 纠错级别
[ewmFilter setValue:@"M" forKey:@"inputCorrectionLevel"];
return ewmFilter.outputImage;
}
生成CIImage
, 参数string
就是需要生成二维码的内容
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
// 位图
CGRect extent = CGRectIntegral(image.extent);
CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
size_t width = CGRectGetWidth(extent) * scale;
size_t height = CGRectGetHeight(extent) * scale;
CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
CIContext *context = [CIContext contextWithOptions:nil];
CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
CGContextScaleCTM(bitmapRef, scale, scale);
CGContextDrawImage(bitmapRef, extent, bitmapImage);
// 保存bitmap到图片
CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
CGContextRelease(bitmapRef);
CGImageRelease(bitmapImage);
return [UIImage imageWithCGImage:scaledImage];
}
用生成的CIImage
来生成UIImage
, 稍微强调下, 传入的size
参数决定了图片的大小, 因为借助UIImageView
来显示, 所以UIImageView.frame
相同, size
越大, 二维码图片越清晰.
void ProviderReleaseData (void *info, const void *data, size_t size) {
free((void*)data);
}
- (UIImage*)imageBlackToTransparent:(UIImage*)image withRed:(CGFloat)red andGreen:(CGFloat)green andBlue:(CGFloat)blue {
const int imageWidth = image.size.width;
const int imageHeight = image.size.height;
size_t bytesPerRow = imageWidth * 4;
uint32_t *rgbImageBuf = (uint32_t *)malloc(bytesPerRow * imageHeight);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(rgbImageBuf, imageWidth, imageHeight, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), image.CGImage);
int pixelNum = imageWidth * imageHeight;
uint32_t *pCurPtr = rgbImageBuf;
for (int i = 0; i < pixelNum; i++, pCurPtr++) {
if ((*pCurPtr & 0xFFFFFF00) < 0x99999900) {
// 改成下面的代码,会将图片转成想要的颜色
uint8_t *ptr = (uint8_t *)pCurPtr;
ptr[3] = red; //0~255
ptr[2] = green;
ptr[1] = blue;
}
else {
uint8_t *ptr = (uint8_t *)pCurPtr;
ptr[0] = 0;
}
}
CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, rgbImageBuf, bytesPerRow * imageHeight, ProviderReleaseData);
CGImageRef imageRef = CGImageCreate(imageWidth, imageHeight, 8, 32, bytesPerRow, colorSpace, kCGImageAlphaLast | kCGBitmapByteOrder32Little, dataProvider, NULL, true, kCGRenderingIntentDefault);
CGDataProviderRelease(dataProvider);
UIImage *resultUIImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
return resultUIImage;
}
如果想更改二维码颜色, 就把UIImage
及颜色传入这个方法, 用新生成的UIImage
赋给ImageView.image
.
最后用一个UIImageView
接收生成的UIImage
, 并且
imageView.contentMode = UIViewContentModeScaleAspectFit;
就可以了.
扫描二维码
- (BOOL)validateCamera {
return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] &&
[UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}
在进行扫描前要先进行判断是否有相机及后置镜头,
// session
self.session = [[AVCaptureSession alloc] init];
self.session.sessionPreset = AVCaptureSessionPresetHigh; // 采集质量
// device
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
// input
AVCaptureDeviceInput *input = [[AVCaptureDeviceInput alloc] initWithDevice:device error:nil];
if (!input) {
// 没有权限会崩溃
// alert...
return;
}
if ([self.session canAddInput:input]) {
[self.session addInput:input];
}
// output
AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
if ([self.session canAddOutput:output]) {
[self.session addOutput:output];
}
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
[output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode/*二维码*/, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code/*一维码*/]];
// layer
AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
layer.videoGravity = AVLayerVideoGravityResizeAspectFill; // 这句好像没卵用
layer.frame = self.view.layer.bounds;
[self.view.layer insertSublayer:layer atIndex:0];
[self.session startRunning];
需要导入<AVFoundation/AVFoundation.h>
,
并遵守AVCaptureMetadataOutputObjectsDelegate
协议
这里有一个坑, 设置output的MetadataObjectTypes
的时候一定要先写[self.session addOutput:output];
, 否则崩溃.
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
if (metadataObjects > 0) {
[self.session stopRunning];
AVMetadataMachineReadableCodeObject *metadataObject = metadataObjects.firstObject;
NSLog(@"二维码的内容: %@", metadataObject.stringValue);
}
}
然后在代理方法中取到解析出来的二维码内容
另外, 如果想要设置扫描区域的话, 需要改变output.rectOfInterest
属性, 这个属性有点特殊, 并不是正常的CGRect
, 据本人试验, 它的四个参数范围都是[0,1], 分别对应(距离上端,距离左端,高度,宽度)
, 举个例子:
如果我想让扫描区域为屏幕坐标的(50,100,200,200)
, 那么需要如下写:
output.rectOfInterest = CGRectMake(100.f/screenHeight, 50.f/screenWidth, 200.f/screenHeight, 200.f/screenWidth);
至于苹果为什么要这样做, 我表示也不太理解...
iOS7二维码的部分就差不多这样, 具体扫描界面还是要自己画的, 希望对各位有帮助, 有什么错误之处请指出, 毕竟本人只是菜鸡一个. <手动滑稽>