您的位置:首页 > 移动开发 > IOS开发

iOS原生API生成二维码(CIFilter)

2016-02-25 13:38 525 查看
利用系统API生成二维码:

1、根据字符串链接生成CIImage图像(CIImage是CoreImage框架中最基本的代表图像的对象,它主要通过CIContext进行渲染,在被渲染之前依赖于滤镜链)

- (CIImage *)createQRForString:(NSString *)qrString {
// Need to convert the string to a UTF-8 encoded NSData object
NSData *stringData = [qrString dataUsingEncoding:NSUTF8StringEncoding];
// Create the filter
CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
// Set the message content and error-correction level
[qrFilter setValue:stringData forKey:@"inputMessage"];
[qrFilter setValue:@"M" forKey:@"inputCorrectionLevel"];
// Send the image back
return qrFilter.outputImage;
}

2、通过CIContext对所得CIImage图像进行渲染并得到UIImage图像

- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
CGRect extent = CGRectIntegral(image.extent);
CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
// create a bitmap image that we'll draw into a bitmap context at the desired size;
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);
// Create an image with the contents of our bitmap
CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
// Cleanup
CGContextRelease(bitmapRef);
CGImageRelease(bitmapImage);
return [UIImage imageWithCGImage:scaledImage];
}


3、如果需要实现二维码中间带有小图标的则需要在得到二维码之后,将小图标绘制到二维码中间

- (UIImage *)drawIconView:(NSString *)iconName onImage:(UIImage *)image{

// 开启图片上下文
UIGraphicsBeginImageContext(image.size);

// 将图片画到上下文中
[image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];

// 根据图标名称生成图片,并且将图片画到上下文中
UIImage *iconImage = [UIImage imageNamed:iconName];
CGFloat width = 60;
CGFloat height = 60;
CGFloat x = (image.size.width - width) * 0.5;
CGFloat y = (image.size.height - height) * 0.5;
[iconImage drawInRect:CGRectMake(x, y, width, height)];

// 获取图片
UIImage *drawImage = UIGraphicsGetImageFromCurrentImageContext();

// 关闭上下文
UIGraphicsEndImageContext();

return drawImage;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: