生成一個(gè)二維碼的小demo,只需要傳入url網(wǎng)址就行了.
- (UIImage*)getImageWith:(NSString*)url{
// 1志衍、創(chuàng)建濾鏡對(duì)象
CIFilter*filter = [CIFilterfilterWithName:@"CIQRCodeGenerator"];
//恢復(fù)濾鏡的默認(rèn)屬性
[filtersetDefaults];
// 2关噪、設(shè)置數(shù)據(jù)
NSString*string_data = url;
//將字符串轉(zhuǎn)換成NSdata (雖然二維碼本質(zhì)上是字符串,但是這里需要轉(zhuǎn)換,不轉(zhuǎn)換就崩潰)
NSData*qrImageData = [string_datadataUsingEncoding:NSUTF8StringEncoding];
//設(shè)置過濾器的輸入值, KVC賦值
[filtersetValue:qrImageDataforKey:@"inputMessage"];
// 3、獲得濾鏡輸出的圖像
CIImage*outputImage = [filteroutputImage];
//圖片小于(27,27),我們需要放大
outputImage = [outputImageimageByApplyingTransform:CGAffineTransformMakeScale(20,20)];
// 4锅尘、將CIImage類型轉(zhuǎn)成UIImage類型
UIImage*start_image = [UIImageimageWithCIImage:outputImage];
// - - - - - - - - - - - - - - - -添加中間小圖標(biāo)- - - - - - - - - - - - - - - -
// 5顷蟆、開啟繪圖,獲取圖形上下文(上下文的大小,就是二維碼的大小)
UIGraphicsBeginImageContext(start_image.size);
//把二維碼圖片畫上去(這里是以圖形上下文,左上角為(0,0)點(diǎn)
[start_imagedrawInRect:CGRectMake(0,0, start_image.size.width, start_image.size.height)];
//再把小圖片畫上去
NSString*icon_imageName =@"520";
UIImage*icon_image = [UIImageimageNamed:icon_imageName];
CGFloaticon_imageW =200;
CGFloaticon_imageH = icon_imageW;
CGFloaticon_imageX = (start_image.size.width- icon_imageW) *0.5;
CGFloaticon_imageY = (start_image.size.height- icon_imageH) *0.5;
[icon_imagedrawInRect:CGRectMake(icon_imageX, icon_imageY, icon_imageW, icon_imageH)];
// 6修壕、獲取當(dāng)前畫得的這張圖片
UIImage*final_image =UIGraphicsGetImageFromCurrentImageContext();
// 7、關(guān)閉圖形上下文
UIGraphicsEndImageContext();
// 8凤藏、借助UIImageView顯示二維碼
return_qrCodeImage.image= final_image;
//CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
//NSData *data = [url dataUsingEncoding:NSUTF8StringEncoding];
//[filter setValue:data forKey:@"inputMessage"];
//CIImage *outImage = filter.outputImage;
//CIContext *context = [CIContext contextWithOptions:nil];
//CGRect extent = outImage.extent;
//CGImageRef bitmapImage = [context createCGImage:outImage fromRect:extent];
//CGFloat scale = MIN(250/CGRectGetWidth(extent), 250/CGRectGetHeight(extent));
//CGContextRef bitmapRef = CGBitmapContextCreate(nil, 250, 250, 8, 0, CGColorSpaceCreateDeviceGray(), (CGBitmapInfo)kCGImageAlphaNone);
//CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
//CGContextScaleCTM(bitmapRef, scale, scale);
//CGContextDrawImage(bitmapRef, extent, bitmapImage);
//CGImageRef scaleImage = CGBitmapContextCreateImage(bitmapRef);
//CGContextRelease(bitmapRef);
//CGImageRelease(bitmapImage);
//return _qrCodeImage.image = [UIImage imageWithCGImage:scaleImage];
}
最后運(yùn)行結(jié)果如下圖: