混淆的驗證碼視圖,是我們日常經常用到的功能模塊之一,一般來說后臺不會直接返回我們驗證碼的圖片,一般需要我們將字符串信息轉換成我們需要的視圖;不管是轉換成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();
}