iOS中的原生架構產生二維碼

來源:互聯網
上載者:User

標籤:

一、二維碼的產生
  • 從iOS7開始整合了二維碼的產生和讀取功能
  • 此前被廣泛使用的ZBarSDK 目前不支援64位處理器,除此之外還有ZXingSDK也可以產生二維碼
  • 產生二維碼的步驟
    • 匯入CoreImage架構
    • 通過濾鏡CIFilter產生二維碼  
  • 二維碼的內容(傳統的條碼只能放數字)
    • 純文字
    • 名片
    • URL(可直接跳轉網頁)

 

 

二維碼產生的具體代碼

 

 1 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { 2      3     //建立過濾器 4     CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"]; 5      6     //過濾器恢複預設 7     [filter setDefaults]; 8      9     //給過濾器添加資料10     NSString *string = @"http://www.cnblogs.com/PSSSCode/";11     12     //將NSString格式轉化成NSData格式13     NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];14     15     [filter setValue:data forKeyPath:@"inputMessage"];16     17     //擷取二維碼過濾器產生的二維碼18     CIImage *image = [filter outputImage];19     20     //將擷取到的二維碼添加到imageview上21     self.imageView.image =[UIImage imageWithCIImage:image];

從可以看出產生的二維碼模糊不清晰,在上面代碼塊最後一步換成調用下面代碼塊中的方法即可

 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.