swift 绘制二维码

导语

网上二维码生成的demo有很多了,自己用swift写了一个,不多说,直接贴效果图,上代码

QQ20170609-105035.gif

生成二维码

    fileprivate func creatCIImage(string: String) -> CIImage? {
        //creat 二维码滤镜
        let filter = CIFilter(name: "CIQRCodeGenerator")
        //恢复默认属性
        filter?.setDefaults()
        let data = string.data(using: .utf8)
        filter?.setValue(data, forKey: "inputMessage")
        //生成二维码
        let ciImage = filter?.outputImage
        return ciImage
    }

重新绘制改变大小

fileprivate func transitionCIImageToUIImage(ciImage: CIImage, size: CGSize) -> UIImage? {
        //获取ciimage的bounds
        let extent = ciImage.extent
        //获取缩放比例
        let scale = min(size.width / extent.width, size.height / extent.height) * UIScreen.main.scale
        //创建bitmap(位图)
        let context = CIContext(options: nil)
        guard let bitImage = context.createCGImage(ciImage, from: extent) else { return nil }
        
        let width = extent.width * scale
        let height = extent.height * scale
        //创建灰度空间
        let cs = CGColorSpaceCreateDeviceGray()
        //创建位图上下文
        let bitRef = CGContext.init(data: nil, width:Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: cs, bitmapInfo: CGImageAlphaInfo.none.rawValue)
        bitRef?.interpolationQuality = .none
        bitRef?.scaleBy(x: scale, y: scale)
        bitRef?.draw(bitImage, in: extent)
        //绘制
        guard let scaleImage = bitRef?.makeImage() else { return nil }
        
        let image = UIImage.init(cgImage: scaleImage)
        
        return image
    }

合成中间logo

fileprivate func syntheticTwoImages(qRImage: UIImage, headerImage: UIImage) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(qRImage.size, false, 0)
        
        let qrSizeWidth = qRImage.size.width / qRImage.scale
        let qrSizeHeight = qRImage.size.height / qRImage.scale
        let headerFrame = CGRect(x: qrSizeWidth / 3, y: qrSizeHeight / 3, width: qrSizeWidth / 3, height: qrSizeHeight / 3)
        
        qRImage.draw(in: CGRect(x: 0, y: 0, width: qrSizeWidth, height: qrSizeHeight))
        headerImage.draw(in: headerFrame)
        
        let syntheticImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return syntheticImage
    }

你可能感兴趣的:(swift 绘制二维码)