首先 导入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
}
原文:http://www.cnblogs.com/hongShuShu/p/4508901.html