iOS-二维码和条形码的生成

调用的方法

- (void)refreshState{

CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];

// 2.恢复默认

[filter setDefaults];

// 3.给过滤器添加数据

NSString * dataString = @"hahahahhahahahahahahahahahahahhahahahahahaahha";

NSData  * data = [dataString dataUsingEncoding:NSUTF8StringEncoding];

// 4.通过KVO设置滤镜inputMessage数据

[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];

}

生成的方法


/**

* 根据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.创建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];

}

你可能感兴趣的:(iOS-二维码和条形码的生成)