Swift - 生成二维码

前端之家收集整理的这篇文章主要介绍了Swift - 生成二维码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
CIFilter 提供了各种各样的滤镜,其中 CIQRCodeGenerator 可以用来生成二维码。下面通过一个样例演示如何将字符串(链接也是字符串)生成二维码图片,同时支持二维码中间放置个性化图标。

效果图如下:
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import UIKit
class ViewController : UIViewController {
override func viewDidLoad() {
super .viewDidLoad()
let imageViewIcon1 = UIImageView (frame: CGRectMake (20,150,150))
imageViewIcon1.image = createQRForString( "http://www.hangge.com" ,
qrImageName: "" )
self .view.addSubview(imageViewIcon1)
imageViewIcon2 = (frame: CGRectMake (200,150))
imageViewIcon2.image = createQRForString( "logo" )
.view.addSubview(imageViewIcon2)
}
createQRForString(qrString: String ?,qrImageName: ?) -> UIImage ?{
if sureQRString = qrString {
stringData = sureQRString.dataUsingEncoding( NSUTF8StringEncoding allowLossyConversion: false )
// 创建一个二维码的滤镜
qrFilter = CIFilter (name: "CIQRCodeGenerator" )!
qrFilter.setValue(stringData,forKey: "inputMessage" )
qrFilter.setValue( "H" "inputCorrectionLevel" )
qrCIImage = qrFilter.outputImage
// 创建一个颜色滤镜,黑白色
colorFilter = "CIFalseColor" )!
colorFilter.setDefaults()
colorFilter.setValue(qrCIImage,monospace!important; min-height:auto!important; color:blue!important; background:none!important">"inputImage" )
colorFilter.setValue( CIColor (red: 0,green: 0,blue: 0),monospace!important; min-height:auto!important; color:blue!important; background:none!important">"inputColor0" )
(red: 1,green: 1,blue: 1),monospace!important; min-height:auto!important; color:blue!important; background:none!important">"inputColor1" )
// 返回二维码image
codeImage = ( CIImage : colorFilter.outputImage!
.imageByApplyingTransform( CGAffineTransformMakeScale (5,5)))
// 通常,二维码都是定制的,中间都会放想要表达意思的图片
iconImage = (named: qrImageName!) {
rect = (0,codeImage.size.width,codeImage.size.height)
UIGraphicsBeginImageContext (rect.size)
codeImage.drawInRect(rect)
avatarSize = CGSizeMake (rect.size.width * 0.25,rect.size.height * 0.25)
x = (rect.width - avatarSize.width) * 0.5
y = (rect.height - avatarSize.height) * 0.5
iconImage.drawInRect( (x,y,avatarSize.width,avatarSize.height))
resultImage = UIGraphicsGetImageFromCurrentImageContext ()
UIGraphicsEndImageContext ()
return resultImage
}
codeImage
}
return nil
}
didReceiveMemoryWarning() {
.didReceiveMemoryWarning()
}
}

原文出自: www.hangge.com 转载请保留原文链接 http://www.hangge.com/blog/cache/detail_909.html

猜你在找的Swift相关文章