調(diào)用的方法
- (void)refreshState{
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
// 2.恢復(fù)默認(rèn)
[filter setDefaults];
// 3.給過濾器添加數(shù)據(jù)
NSString * dataString = @"hahahahhahahahahahahahahahahahhahahahahahaahha";
NSData? * data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
// 4.通過KVO設(shè)置濾鏡inputMessage數(shù)據(jù)
[filter setValue:data forKeyPath:@"inputMessage"];
// 4.獲取輸出的二維碼
CIImage *outputImage = [filter outputImage];
//生成二維碼
self.imgCodeQR.image = [TicketsCodeModel createNonInterpolatedUIImageFormCIImage:outputImage withSize:200];
//生成條形碼
self.imgCodeBar.image = [TicketsCodeModel generateBarCode:@"1234948958096" width:200 height:100];
}
生成的方法
/**
* 根據(jù)CIImage生成指定大小的UIImage
*
* @param image CIImage
* @param size 圖片寬度
*/
+ (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size
{
CGRect extent = CGRectIntegral(image.extent);
CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
// 1.創(chuàng)建bitmap;
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);
// 2.保存bitmap到圖片
CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
CGContextRelease(bitmapRef);
CGImageRelease(bitmapImage);
return [UIImage imageWithCGImage:scaledImage];
}
+(UIImage*)generateBarCode:(NSString*)barCodeStr width:(CGFloat)width height:(CGFloat)height
{
// 生成二維碼圖片
CIImage *barcodeImage;
NSData *data = [barCodeStr dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:false];
CIFilter *filter = [CIFilter filterWithName:@"CICode128BarcodeGenerator"];
[filter setValue:data forKey:@"inputMessage"];
barcodeImage = [filter outputImage];
// 消除模糊
CGFloat scaleX = width / barcodeImage.extent.size.width; // extent 返回圖片的frame
CGFloat scaleY = height / barcodeImage.extent.size.height;
CIImage *transformedImage = [barcodeImage imageByApplyingTransform:CGAffineTransformScale(CGAffineTransformIdentity, scaleX, scaleY)];
return [UIImage imageWithCIImage:transformedImage];
}