swift 3.0 Xcode 8.1
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel.init(frame: CGRect.init(x: 50, y: 100, width: 200, height: 21))
label.text = "my name is Apple"
self.view.addSubview(label)
let imageView = UIImageView.init(frame: CGRect.init(x: 50, y: 200, width: 300, height: 300))
imageView.backgroundColor = UIColor.gray
self.view.addSubview(imageView)
//添加二維碼圖片
imageView.image = self.creatQRCodeImage(text: label.text!)
}
//MARK: -傳進去字符串,生成二維碼圖片
func creatQRCodeImage(text: String) -> UIImage{
//建立濾鏡
let filter = CIFilter(name: "CIQRCodeGenerator")
//還原濾鏡的默認屬性
filter?.setDefaults()
//設置須要生成二維碼的數據
filter?.setValue(text.data(using: String.Encoding.utf8), forKey: "inputMessage")
//從濾鏡中取出生成的圖片
let ciImage = filter?.outputImage
//把CIImage轉成UIImage
//let bgImage = UIImage.init(ciImage: ciImage!) //這個清晰度很差
let bgImage = createNonInterpolatedUIImageFormCIImage(image: ciImage!, size: 300) //這個清晰度好
//建立一個頭像
let icon = UIImage(named: "123.jpg")
//合成圖片(把二維碼和頭像合併)
let newImage = creatImage(bgImage: bgImage, iconImage: icon!)
//返回生成好的二維碼
return newImage
}
//MARK: - 根據CIImage生成指定大小的高清UIImage
func createNonInterpolatedUIImageFormCIImage(image: CIImage, size: CGFloat) -> UIImage {
//CIImage沒有frame與bounds屬性,只有extent屬性
let ciextent: CGRect = image.extent.integral
let scale: CGFloat = min(size/ciextent.width, size/ciextent.height)
let context = CIContext(options: nil) //建立基於GPU的CIContext對象,性能和效果更好
let bitmapImage: CGImage = context.createCGImage(image, from: ciextent)! //CIImage->CGImage
let width = ciextent.width * scale
let height = ciextent.height * scale
let cs: CGColorSpace = CGColorSpaceCreateDeviceGray() //灰度顏色通道
let info_UInt32 = CGImageAlphaInfo.none.rawValue
let bitmapRef = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: cs, bitmapInfo: info_UInt32)! //圖形上下文,畫布
bitmapRef.interpolationQuality = CGInterpolationQuality.none //寫入質量
bitmapRef.scaleBy(x: scale, y: scale) //調整「畫布」的縮放
bitmapRef.draw(bitmapImage, in: ciextent) //繪製圖片
let scaledImage: CGImage = bitmapRef.makeImage()! //保存
return UIImage(cgImage: scaledImage)
}
//MARK: - 根據背景圖片和頭像合成頭像二維碼
func creatImage(bgImage: UIImage, iconImage:UIImage) -> UIImage{
//開啓圖片上下文
UIGraphicsBeginImageContext(bgImage.size)
//繪製背景圖片
bgImage.draw(in: CGRect(origin: CGPoint.zero, size: bgImage.size))
//繪製頭像
let width: CGFloat = 50
let height: CGFloat = width
let x = (bgImage.size.width - width) * 0.5
let y = (bgImage.size.height - height) * 0.5
iconImage.draw(in: CGRect(x: x, y: y, width: width, height: height))
//取出繪製好的圖片
let newImage = UIGraphicsGetImageFromCurrentImageContext()
//關閉上下文
UIGraphicsEndImageContext()
//返回合成好的圖片
return newImage!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}