import UIKit
class CaptchaView: UIView {
private let characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
private let numberOfCharacters = 6
private let fontSize: CGFloat = 20.0
private var captchaText: String = ""
override func awakeFromNib() {
super.awakeFromNib()
generateCaptcha()
backgroundColor = UIColor.lightGray
}
// 生成隨機的驗證碼
private func generateCaptcha() {
captchaText = ""
for _ in 0..<numberOfCharacters {
let randomIndex = Int(arc4random_uniform(UInt32(characters.count)))
let randomCharacter = characters[characters.index(characters.startIndex, offsetBy: randomIndex)]
captchaText.append(randomCharacter)
}
setNeedsDisplay()
}
override func draw(_ rect: CGRect) {
super.draw(rect)
guard let context = UIGraphicsGetCurrentContext() else {
return
}
let width = rect.size.width / CGFloat(numberOfCharacters)
for (index, character) in captchaText.enumerated() {
let x = CGFloat(index) * width
let y = rect.size.height / 2 - fontSize / 2
let font = UIFont.systemFont(ofSize: fontSize)
let attributes: [NSAttributedString.Key: Any] = [
.font: font,
.foregroundColor: UIColor.black
]
let attributedString = NSAttributedString(string: String(character), attributes: attributes)
let characterRect = CGRect(x: x, y: y, width: width, height: fontSize)
attributedString.draw(in: characterRect)
}
}
}
在上述代碼中,CaptchaView是一個繼承自UIView的自定義視圖丹莲,用于展示圖形驗證碼。在awakeFromNib()方法中,我們調(diào)用generateCaptcha()生成隨機的驗證碼并設(shè)置背景色堡僻。在draw(_:)方法中,我們使用Core Graphics繪制驗證碼的每個字符疫剃,并將其居中顯示在視圖中钉疫。你可以將CaptchaView添加到你的iOS應(yīng)用程序的界面中,然后就可以看到生成的圖形驗證碼了巢价。