1 -(void)generatingTwoDimensionalCode { 2 3 // 建立過濾器 4 CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"]; 5 6 // 過濾器恢復默認 7 [filter setDefaults]; 8 9 // 給過濾器添加數據 10 NSString *string = @"https://www.baidu.com"; // 以百度爲例 11 NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; 12 13 [filter setValue:data forKeyPath:@"inputMessage"]; 14 15 // 獲取二維碼過濾器生成的二維碼 16 CIImage *image = [filter outputImage];// 此時的 image 是模糊的 17 18 // 高清處理:將獲取到的二維碼添加到 imageview 19 self.imageView.image =[self createNonInterpolatedUIImageFormCIImage:image withSize:300];// withSize 大於等於視圖顯示的尺寸 20 } 21 22 //--生成高清二維碼 23 - (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size { 24 25 CGRect extent = CGRectIntegral(image.extent); 26 CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent)); 27 28 // 建立 bitmap 29 size_t width = CGRectGetWidth(extent) * scale; 30 size_t height = CGRectGetHeight(extent) * scale; 31 CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray(); 32 CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone); 33 CIContext *context = [CIContext contextWithOptions:nil]; 34 CGImageRef bitmapImage = [context createCGImage:image fromRect:extent]; 35 CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone); 36 CGContextScaleCTM(bitmapRef, scale, scale); 37 CGContextDrawImage(bitmapRef, extent, bitmapImage); 38 39 // 保存 bitmap 到圖片 40 CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef); 41 CGContextRelease(bitmapRef); 42 CGImageRelease(bitmapImage); 43 return [UIImage imageWithCGImage:scaledImage]; 44 }