你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> IOS Swift 開發QRCore(二維碼)實例詳解

IOS Swift 開發QRCore(二維碼)實例詳解

編輯:IOS開發綜合

1、搭個界面


2、寫代碼

// 
// ViewController.swift 
// GeneratorQRCode 
// 
// Created by targetcloud on 2016/12/3. 
// Copyright © 2016年 targetcloud. All rights reserved. 
// 
 
import UIKit 
 
class ViewController: UIViewController { 
  @IBOutlet weak var qrImg: UIImageView! 
  @IBOutlet weak var qrContent: UITextView! 
 
  @IBAction func generatorQRImg(_ sender: Any) { 
    view.endEditing(true) 
    let str = qrContent.text ?? "" 
     
    let filter = CIFilter(name: "CIQRCodeGenerator") 
    filter?.setDefaults() 
    let data = str.data(using: String.Encoding.utf8) 
    filter?.setValue(data, forKey: "inputMessage") 
    filter?.setValue("M", forKey: "inputCorrectionLevel") 
    var image = filter?.outputImage 
    let transform = CGAffineTransform(scaleX: 10, y: 10)//處理成為一個高清圖片 
    image = image?.applying(transform) 
    var resultImage = UIImage(ciImage: image!) 
     
    let centerImg = UIImage(named: "targetcloud.png") 
    resultImage = mergeImage(resultImage, centerImg: centerImg!, drawSize:CGSize(width: 80, height: 80)) 
    qrImg.image = resultImage 
  } 
   
  func mergeImage(_ sourceImage: UIImage, centerImg: UIImage,drawSize:CGSize) -> UIImage { 
    let size = sourceImage.size 
    UIGraphicsBeginImageContext(size) 
    sourceImage.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) 
    centerImg.draw(in: CGRect(x: (size.width - drawSize.width) * 0.5, y: (size.height - drawSize.height) * 0.5, width: drawSize.width, height: drawSize.height)) 
    let resultImage = UIGraphicsGetImageFromCurrentImageContext() 
    UIGraphicsEndImageContext() 
    return resultImage! 
  } 
} 

3、運行效果



感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved