混淆的验证码视图,是我们日常经常用到的功能模块之一,一般来说后台不会直接返回我们验证码的图片,一般需要我们将字符串信息转换成我们需要的视图;不管是转换成View还是button,这里介绍一个比较简单的方法,重写
override func draw(_ rect: CGRect)
这里一般需要两个步骤,一是重写字符串的字体大小、颜色、样式等
首先计算每个字符显示的位置
let text :String = String.init(format: "\(self.verifyCode)")
let cSize: CGSize = "A".size(attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 20)])
let width = rect.size.width/CGFloat(text.characters.count) - cSize.width
let hight = rect.size.height - cSize.height
设置字符串的字体大小、颜色
for index in 0..<text.characters.count {
pX = CGFloat(arc4random()%UInt32(width)) + rect.size.width/CGFloat(text.characters.count)*CGFloat(index)
pY = CGFloat(arc4random()%UInt32(hight))
point = CGPoint(x: pX!, y: pY!)
let c = text.index(text.startIndex, offsetBy: index)
let textC :String = String.init(format: "%C", c as! CVarArg)
let randomFont = UIFont.systemFont(ofSize:CGFloat(arc4random()%5+15))
textC.draw(at: point!, withAttributes: [NSFontAttributeName:randomFont])
}
当然这样还是完全不够的,还需要我们绘制干扰线
let context = UIGraphicsGetCurrentContext()
context!.setLineWidth(CGFloat(kLineWith));
for _ in 0..<kLineCount {
let randomCorlor = UIColor.init(colorLiteralRed: Float(arc4random()%255)/Float(255.0), green: Float(arc4random()%255)/Float(255.0), blue: Float(arc4random()%255)/Float(255.0), alpha: 1.0)
context?.setStrokeColor(randomCorlor.cgColor)
//起点
pX = CGFloat(arc4random()%UInt32(rect.size.width))
pY = CGFloat(arc4random()%UInt32(rect.size.height))
context?.move(to: CGPoint(x: pX!, y: pY!))
//终点
pX = CGFloat(arc4random()%UInt32(rect.size.width))
pY = CGFloat(arc4random()%UInt32(rect.size.height))
context?.addLine(to: CGPoint(x: pX!, y: pY!))
context?.strokePath();
}