private func creatQRCodeImage(text: String) -> UIImage{
//创建滤镜
let filter = CIFilter(name: "CIQRCodeGenerator")
//还原滤镜的默认属性
filter?.setDefaults()
filter?.setValue(text.dataUsingEncoding(NSUTF8StringEncoding),forKey: "inputMessage")
let ciImage = filter?.outputImage
//这个清晰度不好
//let bgImage = UIImage(CIImage: ciImage!)
//这个清晰度好
let bgImage = createNonInterpolatedUIImageFormCIImage(ciImage!,size: 300)
//创建一个头像
let icon = UIImage(named: "navigationbar_pop_highlighted")
let newImage = creatImage(bgImage,iconImage: icon!)
return newImage
}
private func creatImage(bgImage: UIImage,iconImage:UIImage) -> UIImage{
//开启图片上下文
UIGraphicsBeginImageContext(bgImage.size)
//绘制背景图片
bgImage.drawInRect(CGRect(origin: CGPointZero,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.drawInRect(CGRect(x: x,y: y,width: width,height: height))
//取出绘制好的图片
let newImage = UIGraphicsGetImageFromCurrentImageContext()
//关闭上下文
UIGraphicsEndImageContext()
//返回合成好的图片
return newImage
}
//MARK: -根据CIImage生成指定大小的高清UIImage
private func createNonInterpolatedUIImageFormCIImage(image: CIImage,size: CGFloat) -> UIImage {
let extent: CGRect = CGRectIntegral(image.extent)
let scale: CGFloat = min(size/CGRectGetWidth(extent),size/CGRectGetHeight(extent))
let width = CGRectGetWidth(extent) * scale
let height = CGRectGetHeight(extent) * scale
let cs: CGColorSpaceRef = CGColorSpaceCreateDeviceGray()!
let bitmapRef = CGBitmapContextCreate(nil,Int(width),Int(height),8,cs,0)!
let context = CIContext(options: nil)
let bitmapImage: CGImageRef = context.createCGImage(image,fromRect: extent)
CGContextSetInterpolationQuality(bitmapRef,CGInterpolationQuality.None)
CGContextScaleCTM(bitmapRef,scale,scale);
CGContextDrawImage(bitmapRef,extent,bitmapImage);
let scaledImage: CGImageRef = CGBitmapContextCreateImage(bitmapRef)!
return UIImage(CGImage: scaledImage)
}
原文链接:https://www.f2er.com/swift/324179.html