小编给大家分享一下iOS如何生成图片验证码,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
1.数据源
codeArray = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
2.随机生成验证码
for index in 0..<4 {
let i = (Int)(arc4random()) % (codeArray.count-1)
let str = codeArray[i]
if index == 0 {
codeStr = str as NSString
}else {
codeStr = "\(codeStr)\(str)" as NSString
}
}
3.创建放置验证码的label
for i in 0..<codeStr.length {
let pxx = arc4random() % UInt32(randWidth)
let px = CGFloat(pxx) + CGFloat(i)*(self.frame.size.width-3)/CGFloat(codeStr.length)
let py = arc4random() % UInt32(randHeight)
let label = UILabel.init(frame: CGRect.init(x: px + 3, y: CGFloat(py), width: textSize.width, height: textSize.height))
label.text = String.init(format: "%C", codeStr.character(at: i))
label.font = UIFont.systemFont(ofSize: 20)
if (isRotation == true) {
let a = arc4random() % UInt32(60)
let r = Double(a)-30
label.transform = CGAffineTransform.init(rotationAngle: CGFloat(r*M_PI)/180)
}
bgView.addSubview(label)
}
4.底部view是随便画几条细线
for _ in 0...9 {
let path = UIBezierPath.init()
let pX = arc4random() % UInt32(self.frame.width)
let pY = arc4random() % UInt32(self.frame.height)
path.move(to: CGPoint.init(x: CGFloat(pX), y: CGFloat(pY)))
let ptX = arc4random() % UInt32(self.frame.width)
let ptY = arc4random() % UInt32(self.frame.height)
path.addLine(to: CGPoint.init(x: CGFloat(ptX), y: CGFloat(ptY)))
let layer = CAShapeLayer.init()
layer.strokeColor = UIColor.getRandomColor(withAlpha: 0.2).cgColor//layer的边框色
layer.lineWidth = 1.0
layer.strokeEnd = 1
layer.fillColor = UIColor.clear.cgColor
layer.path = path.cgPath
bgView.layer.addSublayer(layer)
}
5.调用方法及回调
public func refreshCode(callBack: @escaping (_ str: NSString) -> ()) {
initCodeView()
callBack(codeStr)
}
6.效果图
以上是“iOS如何生成图片验证码”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。