swift 文字验证码
这个demo的主要功能是用于防止有人浪用接口,频繁的去请求接口。实现的主要原理如下:
1.创建一个用来验证的字符串
func getAuthcode() {
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"]
for _ in 0..<6//需要多少个字符来验证
{
let num = codeArray.count-1
let y = Int(arc4random_uniform(UInt32(num)))
let tempStr = codeArray[y]
if codeString == nil {
codeString = tempStr
}else{
codeString = codeString! + tempStr
}}}
2.为这个字符串创建一个视图
override func draw(_ rect: CGRect) {
super.draw(rect)
self.backgroundColor = UIColor.init(red: CGFloat(Double(arc4random()%256)/256.0) , green: CGFloat(Double(arc4random()%256)/256.0) , blue: CGFloat(Double(arc4random()%256)/256.0) , alpha: 1.0)
let cSize = ("A" as NSString).size(attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 20)])
let width = rect.size.width/CGFloat((codeString! as NSString).length) - cSize.width
let height = rect.size.height - cSize.height
var point:CGPoint?
var x:CGFloat = 0.0
var y:CGFloat = 0.0
for index in 0..<(codeString! as NSString).length {
x = CGFloat(arc4random_uniform(UInt32(width))) + rect.size.width/CGFloat((codeString! as NSString).length)*CGFloat(index)
y = CGFloat(arc4random_uniform(UInt32(height)))
point = CGPoint.init(x: x, y: y)
let c = (codeString! as NSString).character(at: index)
let textC:String = String(Character(UnicodeScalar(c)!))
(textC as NSString).draw(at: point!, withAttributes: [NSFontAttributeName:UIFont.systemFont(ofSize: CGFloat(arc4random_uniform(UInt32(5)) + 15))])
}
let context = UIGraphicsGetCurrentContext()
context?.setLineWidth(1.0)
for _ in 0..<5//线条数量
{
let color = UIColor.init(red: CGFloat(Double(arc4random()%256)/256.0) , green: CGFloat(Double(arc4random()%256)/256.0) , blue: CGFloat(Double(arc4random()%256)/256.0) , alpha: 1.0)
context?.setStrokeColor(color.cgColor)
x = CGFloat(arc4random_uniform(UInt32(rect.size.width)))
y = CGFloat(arc4random_uniform(UInt32(rect.size.height)))
context?.move(to: CGPoint.init(x: x, y: y))
x = CGFloat(arc4random_uniform(UInt32(rect.size.width)))
y = CGFloat(arc4random_uniform(UInt32(rect.size.height)))
context?.addLine(to: CGPoint.init(x: x, y: y))
context?.strokePath()
}}
3.为这个视图添加触摸手势,可以让其更换视图
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
codeString = nil
self.getAuthcode()
self.setNeedsDisplay()
}
4》最后的效果如下: