產生二維碼 - swift

來源:互聯網
上載者:User

標籤:

 

首先 匯入AVFoundation架構

 

    @IBOutlet weak var iconView: UIImageView!

    

    

    override func viewDidLoad() {

        super.viewDidLoad()

 

        createQRCode()

    }

    

    private func createQRCode() {

        // 建立一個濾鏡

        let qrFilter = CIFilter(name: "CIQRCodeGenerator")

        // 重設濾鏡的初始值

        qrFilter.setDefaults()

        

        // 通過KVC設定濾鏡的內容

        qrFilter.setValue("逝水子峰".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true), forKey: "inputMessage")

        

        // 輸出映像

        let ciImage = qrFilter.outputImage

        // 列印產生圖片的大小

        println(ciImage.extent())

        

        // 過濾映像單色彩以及 形變 的濾鏡

        let colorFilter = CIFilter(name: "CIFalseColor")

        colorFilter.setDefaults()

        

        colorFilter.setValue(ciImage, forKey: "inputImage")

        

        // 前景色彩

        colorFilter.setValue(CIColor(red: 0, green: 0, blue: 0), forKey: "inputColor0")

        // 背景色

        colorFilter.setValue(CIColor(red: 1, green: 1, blue: 1), forKey: "inputColor1")

        

        let transform = CGAffineTransformMakeScale(5, 5)

        let transformImage = colorFilter.outputImage.imageByApplyingTransform(transform)

        

        let codeImage = UIImage(CIImage: transformImage)

        let avatarImage = UIImage(named: "avatar")

 

        println(codeImage)

        println("----" + "\(avatarImage)")

 

        

//        iconView.image = UIImage(CIImage: transformImage)

        iconView.image = insertAvaterImage(codeImage!, avatarImage: avatarImage!)

    }

 

    

    /// 合成頭像映像

    private func insertAvaterImage(codeImage: UIImage,avatarImage: UIImage) -> UIImage {

        let size = codeImage.size

        

        // 1.開啟映像上下文

        UIGraphicsBeginImageContext(size)

        

        // 2.繪製二維碼映像

        codeImage.drawInRect(CGRectMake(0, 0, size.width, size.height))

        

        // 3.計算頭像的大小

        let w = size.width * 0.25

        let h = size.height * 0.25

        let x = (size.width -  w) * 0.5

        let y = (size.height - h) * 0.5

        avatarImage.drawInRect(CGRectMake(x, y, w, h))

        

        // 4.從上下文中取出映像

        let image = UIGraphicsGetImageFromCurrentImageContext()

        

        // 5.關閉上下文

        UIGraphicsEndImageContext()

        return image

    }

    

 

產生二維碼 - swift

相關文章

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.