- (IBAction)creatQRImage:(id)sender {
[self.textField resignFirstResponder];
//这里是我放了个TextField的控件,但我们没有输入值得时候就返回
if (self.textField.text.length ==0) {
return;
}
// 1.创建过滤器:做二维码还是条形码的关键CIQRCodeGenerator
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
// 2.恢复默认
[filter setDefaults];
// 3.给过滤器添加数据(正则表达式/账号和密码)
NSString *dataString = self.textField.text;
NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
[filter setValue:data forKeyPath:@"inputMessage"];
// 4.获取输出的二维码
CIImage *outputImage = [filter outputImage];
// 5.将CIImage转换成UIImage,并放大显示
self.imageView.image = [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:200];
}
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size
{
//A rectangle that specifies the extent of the image. (read-only)
//This rectangle specifies the extent of the image in working space coordinates.
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:NSUTF8StringEncoding];
CIFilter * filter = [CIFilter filterWithName:@"CICode128BarcodeGenerator"];
[filter setValue:data forKey:@"inputMessage"];
barcodeImage = [ filter outputImage];
CGFloat scaleX = width / barcodeImage.extent.size.width;
CGFloat scaleY = height / barcodeImage.extent.size.height;
CIImage * transformedImage = [barcodeImage imageByApplyingTransform:CGAffineTransformScale(CGAffineTransformIdentity, scaleX, scaleY)];
return [UIImage imageWithCIImage:transformedImage];
}