標籤:
- (void)viewDidLoad { [super viewDidLoad]; /* 注意: 1.產生二維碼時, 不建議讓二維碼儲存過多資料, 因為資料越多, 那麼二維碼就越密集,那麼掃描起來就越困難 2.二維碼有三個錨點, 著三個錨點不能被遮擋, 否則掃描不出來 3.二維碼即便缺失一部分也能正常掃描出結果, 但是需要注意, 這個缺失的範圍是由限制的, 如果太多那麼也掃面不出來 */ // 1.建立濾鏡 CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"]; // 2.還原濾鏡預設屬性 [filter setDefaults]; // 3.將需要產生二維碼的資料轉換為二進位 NSData *data = [@"123" dataUsingEncoding:NSUTF8StringEncoding]; // 4.給濾鏡設定資料 [filter setValue:data forKeyPath:@"inputMessage"]; // 5.產生圖片 CIImage *qrcodeImage = [filter outputImage]; // 6.顯示圖片// self.qrcodeImageView.image = [UIImage imageWithCIImage:qrcodeImage];// self.qrcodeImageView.image = [self createNonInterpolatedUIImageFormCIImage:qrcodeImage withSize:600]; UIImage *bg = [self createNonInterpolatedUIImageFormCIImage:qrcodeImage withSize:600]; UIImage *icon = [UIImage imageNamed:@"icon"]; self.qrcodeImageView.image = [self creteImageWithBg:bg icon:icon];}- (UIImage *)creteImageWithBg:(UIImage *)bg icon:(UIImage *)icon{ // 1.建立圖形上下文 UIGraphicsBeginImageContextWithOptions(bg.size, YES, 0.0); // 2.繪製背景 [bg drawInRect:CGRectMake(0, 0, bg.size.width, bg.size.height)]; // 3.繪製表徵圖 CGFloat iconW = 60; CGFloat iconH = 60; CGFloat iconX = (bg.size.width - iconW) * 0.5; CGFloat iconY = (bg.size.height - iconH) * 0.5; [icon drawInRect:CGRectMake(iconX, iconY, iconW, iconH)]; // 4.取出圖片 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); // 5.關閉上下文 UIGraphicsEndImageContext(); // 5.返回圖片 return newImage;}/** * 根據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];}
iOS開發之----產生二維碼