欢迎来到代码驿站!

iOS代码

当前位置:首页 > 移动开发 > iOS代码

iOS 生成图片验证码(实用功能)

时间:2021-08-26 08:13:45|栏目:iOS代码|点击:

1.数据源

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"]

2.随机生成验证码

for index in 0..<4 {
      let i = (Int)(arc4random()) % (codeArray.count-1)
      let str = codeArray[i]
      if index == 0 {
        codeStr = str as NSString
      }else {
        codeStr = "\(codeStr)\(str)" as NSString
      }
    }

3.创建放置验证码的label

for i in 0..<codeStr.length {
      let pxx = arc4random() % UInt32(randWidth)
      let px = CGFloat(pxx) + CGFloat(i)*(self.frame.size.width-3)/CGFloat(codeStr.length)
      let py = arc4random() % UInt32(randHeight)
      let label = UILabel.init(frame: CGRect.init(x: px + 3, y: CGFloat(py), width: textSize.width, height: textSize.height))
      label.text = String.init(format: "%C", codeStr.character(at: i))
      label.font = UIFont.systemFont(ofSize: 20)
      if (isRotation == true) {
        let a = arc4random() % UInt32(60)
        let r = Double(a)-30
        label.transform = CGAffineTransform.init(rotationAngle: CGFloat(r*M_PI)/180)
      }
      bgView.addSubview(label)
    }

4.底部view是随便画几条细线

for _ in 0...9 {
      let path = UIBezierPath.init()
      let pX = arc4random() % UInt32(self.frame.width)
      let pY = arc4random() % UInt32(self.frame.height)
      path.move(to: CGPoint.init(x: CGFloat(pX), y: CGFloat(pY)))
      let ptX = arc4random() % UInt32(self.frame.width)
      let ptY = arc4random() % UInt32(self.frame.height)
      path.addLine(to: CGPoint.init(x: CGFloat(ptX), y: CGFloat(ptY)))
      let layer = CAShapeLayer.init()
      layer.strokeColor = UIColor.getRandomColor(withAlpha: 0.2).cgColor//layer的边框色
      layer.lineWidth = 1.0
      layer.strokeEnd = 1
      layer.fillColor = UIColor.clear.cgColor
      layer.path = path.cgPath
      bgView.layer.addSublayer(layer)
    }

5.调用方法及回调

public func refreshCode(callBack: @escaping (_ str: NSString) -> ()) {
    initCodeView()
    callBack(codeStr)
  }

6.效果图

7.源码地址

上一篇:IOS轻松几步实现自定义转场动画

栏    目:iOS代码

下一篇:iOS开发之运动事件和远程控制

本文标题:iOS 生成图片验证码(实用功能)

本文地址:http://www.codeinn.net/misctech/170063.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有