iOS 生成图片验证码(实用功能)
程序员文章站
2023-12-20 16:41:41
1.数据源
codearray = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g...
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 生成图片验证码(实用功能),希望对大家有所帮助