swift系统自带二维码的生成

前端之家收集整理的这篇文章主要介绍了swift系统自带二维码的生成前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

//MARK: -传进去字符串,生成二维码图片

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

}

//MARK: - 根据背景图片和头像合成头像二维码

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

猜你在找的Swift相关文章