1. 程式人生 > >Swift生成二維碼圖片(封裝成了工具類,拿來直接用)

Swift生成二維碼圖片(封裝成了工具類,拿來直接用)

封裝了一個生成二維碼的工具類,使用的時候直接傳參UIImageView和url就可直接生成二維碼後設置上去,簡單方便 !

class QRCodeUtil {
    static func setQRCodeToImageView(_ imageView: UIImageView?, _ url: String?) {
        if imageView == nil || url == nil {
            return
        }
        
        // 建立二維碼濾鏡
        let filter = CIFilter(name: "CIQRCodeGenerator")
        
        // 恢復濾鏡預設設定
        filter?.setDefaults()
        
        // 設定濾鏡輸入資料
        let data = url!.data(using: String.Encoding.utf8)
        filter?.setValue(data, forKey: "inputMessage")
        
        // 設定二維碼的糾錯率
        filter?.setValue("M", forKey: "inputCorrectionLevel")
        
        // 從二維碼濾鏡裡面, 獲取結果圖片
        var image = filter?.outputImage
        
        // 生成一個高清圖片
        let transform = CGAffineTransform.init(scaleX: 20, y: 20)
        image = image?.applying(transform)
        
        // 圖片處理
        var resultImage = UIImage(ciImage: image!)
        
        // 設定二維碼中心顯示的小圖示
        let center = UIImage(named: "AppIcon.png")
        resultImage = getClearImage(sourceImage: resultImage, center: center!)
        
        // 顯示圖片
        imageView?.image = resultImage
    }
    
    // 使圖片放大也可以清晰
    static func getClearImage(sourceImage: UIImage, center: UIImage) -> UIImage {
        
        let size = sourceImage.size
        // 開啟圖形上下文
        UIGraphicsBeginImageContext(size)
        
        // 繪製大圖片
        sourceImage.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        
        // 繪製二維碼中心小圖片
        let width: CGFloat = 80
        let height: CGFloat = 80
        let x: CGFloat = (size.width - width) * 0.5
        let y: CGFloat = (size.height - height) * 0.5
        center.draw(in: CGRect(x: x, y: y, width: width, height: height))
        
        // 取出結果圖片
        let resultImage = UIGraphicsGetImageFromCurrentImageContext()
        
        // 關閉上下文
        UIGraphicsEndImageContext()

        return resultImage!
    }
}