iOS開發--二維碼的產生

來源:互聯網
上載者:User

標籤:

一.需要包含標頭檔

#import <CoreImage/CoreImage.h>

二.範例程式碼 -- 以下產生的二維碼不夠清晰 :

 1 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ 2      3     // 0.匯入標頭檔#import <CoreImage/CoreImage.h> 4      5     // 1.建立過濾器 -- 蘋果沒有將這個字元封裝成常量 6     CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"]; 7      8     // 2.過濾器恢複預設設定 9     [filter setDefaults];10     11     // 3.給過濾器添加資料(Regex/帳號和密碼) -- 通過KVC設定過濾器,只能設定NSData類型12     NSString *dataString = @"http://www.baidu.com";13     NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];14     [filter setValue:data forKeyPath:@"inputMessage"];15     16     // 4.擷取輸出的二維碼17     CIImage *outputImage = [filter outputImage];18     19     // 5.顯示二維碼20     self.imageView.image = [UIImage imageWithCIImage:outputImage];21 }

三.調用下面方法可以產生清晰的二維碼圖片,用的時候也可以給UIImage添加一個分類.這裡沒有抽取分類.:

 1 /** 2  *  根據CIImage產生指定大小的UIImage 3  * 4  *  @param image CIImage 5  *  @param size  圖片寬度 6  */ 7 - (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size 8 { 9     CGRect extent = CGRectIntegral(image.extent);10     CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));11     12     // 1.建立bitmap;13     size_t width = CGRectGetWidth(extent) * scale;14     size_t height = CGRectGetHeight(extent) * scale;15     CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();16     CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);17     CIContext *context = [CIContext contextWithOptions:nil];18     CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];19     CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);20     CGContextScaleCTM(bitmapRef, scale, scale);21     CGContextDrawImage(bitmapRef, extent, bitmapImage);22     23     // 2.儲存bitmap到圖片24     CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);25     CGContextRelease(bitmapRef);26     CGImageRelease(bitmapImage);27     return [UIImage imageWithCGImage:scaledImage];28 }

 

iOS開發--二維碼的產生

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.