由于现在越来越多人使用二维码这个东西, 苹果也在很久之前就推出了二维码的API, 现在让我们一起来看看吧:
PS: 已经更新到Swift 2.0, 支持Xcode7, iOS9
1.布局界面
2.实现代码
关联控件和调用方法
class ViewController: UIViewController {
@IBOutlet var QRImageView: UIImageView!
override func viewDidLoad() { super.viewDidLoad()
QRImageView.image = generateQRImage("哈哈哈哈哈哈", withSizeRate: 10)
}
}
二维码具体方法
func generateQRImage(stringQR:NSString, withSizeRate rate:CGFloat) -> UIImage {
// 1.初始化我们要生成的二维码类型
let filter:CIFilter = CIFilter(name:"CIQRCodeGenerator")!
// 2.把获取到的字符串转成UTF8编码
let data:NSData = stringQR.dataUsingEncoding(NSUTF8StringEncoding)!
// 3.保存到Defaults中
filter.setDefaults()
// 4.把对应的字符串键值对存储到filter中
filter.setValue(data, forKey: "inputMessage")
let outputImg:CIImage = filter.outputImage
let context:CIContext = CIContext(options: nil)
let cgimg:CGImageRef = context.createCGImage(outputImg, fromRect: outputImg.extent)
var img:UIImage = UIImage(CGImage: cgimg, scale: 1.0, orientation: UIImageOrientation.Up)
let width = img.size.width * rate
let height = img.size.height * rate UIGraphicsBeginImageContext(CGSizeMake(width, height))
let cgContxt:CGContextRef = UIGraphicsGetCurrentContext() CGContextSetInterpolationQuality(cgContxt, kCGInterpolationNone)
img.drawInRect(CGRectMake(0, 0, width, height))
img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext()
return img
}
3.最终效果
好了,这次我们就到这里,下次我们继续