swift 5.0 本地随机验证码文本校验效果。
程序员文章站
2022-03-06 17:49:39
...
//
// qshdVerifyCodeView.swift
// qshd
//
// Created by 钟高荣 on 2020/3/12.
// Copyright © 2020 钟高荣. All rights reserved.
//
import UIKit
class qshdVerifyCodeView: UIView {
// 验证码的位数
let charCount = 4
// 混淆的横线个数
let lineCount = 5
// 随机产生的字符串, 由上级界面产生。
var verifyStr:String? {
didSet {
guard verifyStr != nil else {
return
}
self.setNeedsDisplay()
}
}
// MARK: - 重写init方法
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.cornerRadius = 5.0
self.layer.masksToBounds = true
self.backgroundColor = UIColor.muColor(.whiteGray)
}
// MARK: - 重写点击方法重新获取
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// 暂未用到
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// 根据输入的数组获取 0-x 的随机数
func ranNum(num:Int)->Int {
let ranNum = arc4random()%UInt32(num)
return Int(ranNum)
}
override func draw(_ rect: CGRect) {
super.draw(rect)
let ctx = UIGraphicsGetCurrentContext()//获取当前上下文
//2转换坐标
ctx?.textMatrix = CGAffineTransform.identity
ctx?.translateBy(x: 0, y: self.bounds.size.height)
ctx?.scaleBy(x: 1.0, y: -1.0)
// 获取每个字符需要的宽度
let width = (CGFloat)(Int(self.frame.size.width) / self.charCount)
let height = self.frame.size.height
//生成path
let pathText = CGMutablePath()
pathText.addRect(self.bounds)
// 绘制每一个字
for (index,text) in self.verifyStr!.enumerated(){
// 随机x位置
let pX = CGFloat(CGFloat(index) * width + CGFloat(self.ranNum(num: Int(width)) / 2))
// 随机y位置
let pY = CGFloat(self.ranNum(num: 5) - self.ranNum(num: 5))
// 文字大小
let font = UIFont.systemFont(ofSize: 22)
let path1 = UIBezierPath(roundedRect: CGRect.init(x: pX, y: pY, width: width, height: height), cornerRadius: 0).cgPath
let str = String.init(text)
let mutableAttrStr = NSMutableAttributedString(string: str)
mutableAttrStr.addAttributes([NSAttributedString.Key.font:font, NSAttributedString.Key.foregroundColor:UIColor.randomColor], range: NSMakeRange(0, 1))
let frameSetter = CTFramesetterCreateWithAttributedString(mutableAttrStr)
let frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, mutableAttrStr.length), path1, nil)
//绘制文本
CTFrameDraw(frame, ctx!)
}
// 绘制干扰线
for _ in 0..<lineCount {
let path = UIBezierPath()
var pX:CGFloat = 0.0
var pY:CGFloat = 0.0
// 起点
pX = CGFloat(self.ranNum(num: Int(rect.size.width)))
pY = CGFloat(self.ranNum(num: Int(rect.size.height)))
path.move(to: CGPoint(x: pX, y: pY))
// 终点
let ppX = CGFloat(self.ranNum(num: Int(rect.size.width)))
let ppY = CGFloat(self.ranNum(num: Int(rect.size.height)))
path.addLine(to: CGPoint.init(x: ppX, y: ppY))
path.close()
// 随机线颜色
let color = UIColor.randomColor
color.setStroke()
color.setFill()
path.lineWidth = FMPx(1)
path.stroke()
}
}
}
效果如下
上一篇: 夫妻闹别扭
下一篇: Swift入门笔记(一)