swift 生成验证码 - CSDN
  • Swift 生成图形验证码

    2019-10-13 23:54:01
    效果: class ImageCodeVerification: NSObject { static func create(_ frame: CGRect) -> (obj: UIView, code: String) { let code = getCode() let view = getView(frame, code) r...

    效果:
    在这里插入图片描述

    class ImageCodeVerification: NSObject {
    
        static func create(_ frame: CGRect) -> (obj: UIView, code: String) {
            let code = getCode()
            let view = getView(frame, code)
            return (view, code)
        }
    
        private override init() {
            super.init()
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        private static func getCode() -> String {
            let codeArray =  ["0","1","2","3","4","5","6","7","8","9"]
    //        var 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"]
            var codeStr = ""
            for _ in 0 ..< 4 {
                let i = (Int)(arc4random()) % (codeArray.count-1)
                let str = codeArray[i]
                codeStr.append(str)
            }
            return codeStr
        }
    
        private static func getView(_ frame: CGRect, _ codeStr: String) -> UIView {
            let view = UIView(frame: frame)
            var randWidth = frame.width/CGFloat(codeStr.count)/5
            var randHeight = frame.height/5
            if randWidth < 1 {
                randWidth = 1
            }
            if randHeight < 1 {
                randHeight = 1
            }
            let textSize = CGSize(width: frame.width/CGFloat(codeStr.count), height: frame.height/2)
            let isRotation = true
            //创建放置验证码的label
            for i in 0 ..< codeStr.count {
                let pxx = arc4random() % UInt32(randWidth)
                let px = CGFloat(pxx) + CGFloat(i)*(frame.size.width-3)/CGFloat(codeStr.count)
                let py = arc4random() % UInt32(randHeight)
                let label = UILabel.init(frame: CGRect.init(x: px + 3, y: CGFloat(py), width: textSize.width, height: textSize.height))
                let slice = codeStr[codeStr.index(codeStr.startIndex, offsetBy: i) ..< codeStr.index(codeStr.startIndex, offsetBy: i+1)]
                label.text = String.init(slice)
                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*Double.pi)/180)
                }
                view.addSubview(label)
            }
            //随机划线
            for _ in 0...9 {
                let path = UIBezierPath.init()
                let pX = arc4random() % UInt32(view.frame.width)
                let pY = arc4random() % UInt32(view.frame.height)
                path.move(to: CGPoint.init(x: CGFloat(pX), y: CGFloat(pY)))
                let ptX = arc4random() % UInt32(view.frame.width)
                let ptY = arc4random() % UInt32(view.frame.height)
                path.addLine(to: CGPoint.init(x: CGFloat(ptX), y: CGFloat(ptY)))
                let layer = CAShapeLayer.init()
                layer.strokeColor = UIColor.init(white: (CGFloat(arc4random() % 100)/100.0), alpha: 1).cgColor
                layer.lineWidth = 1.0
                layer.strokeEnd = 1
                layer.fillColor = UIColor.clear.cgColor
                layer.path = path.cgPath
                view.layer.addSublayer(layer)
            }
            return view
        }
    
    }
    

    使用方式:

    @IBAction func btnRefreshCodeClicked(_ sender: UIButton) {
            refreshCode()
    }
    
    private func refreshCode() {
            if codeView != nil {
                codeView?.removeFromSuperview()
            }
            let result = ImageCodeVerification.create(CGRect(x: 0, y: 0, width: 80, height: 44))
            codeView = result.obj
            codeString = result.code
            guard codeView != nil && codeString?.count ?? 0 > 0 else {
                return
            }
            codeBackground.addSubview(codeView!)
        }
    
    展开全文
  • iOS随机生成验证码

    2014-05-13 18:02:04
    - (void)onTapToGenerateCode:(UITapGestureRecognizer *)tap { for (UIView *view in self.checkCodeNumberLabel.subviews) { [view removeFromSuperview];... // @name 生成背景色 float red = arc4
    - (void)onTapToGenerateCode:(UITapGestureRecognizer *)tap {
      for (UIView *view in self.checkCodeNumberLabel.subviews) {
        [view removeFromSuperview];
      }
      // @{
      // @name 生成背景色
      float red = arc4random() % 100 / 100.0;
      float green = arc4random() % 100 / 100.0;
      float blue = arc4random() % 100 / 100.0;
      UIColor *color = [UIColor colorWithRed:red green:green blue:blue alpha:0.2];
      [self.checkCodeNumberLabel setBackgroundColor:color];
      // @} end 生成背景色
      
      // @{
      // @name 生成文字
      const int count = 5;
      char data[count];
      for (int x = 0; x < count; x++) {
        int j = '0' + (arc4random_uniform(75));
        if((j >= 58 && j <= 64) || (j >= 91 && j <= 96)){
          --x;
        }else{
          data[x] = (char)j;
        }
      }
      NSString *text = [[NSString alloc] initWithBytes:data
                                                length:count encoding:NSUTF8StringEncoding];
      self.code = text;
      // @} end 生成文字
      
      CGSize cSize = [@"S" sizeWithFont:[UIFont systemFontOfSize:16]];
      int width = self.checkCodeNumberLabel.frame.size.width / text.length - cSize.width;
      int height = self.checkCodeNumberLabel.frame.size.height - cSize.height;
      CGPoint point;
      float pX, pY;
      for (int i = 0, count = text.length; i < count; i++) {
        pX = arc4random() % width + self.checkCodeNumberLabel.frame.size.width / text.length * i - 1;
        pY = arc4random() % height;
        point = CGPointMake(pX, pY);
        unichar c = [text characterAtIndex:i];
        UILabel *tempLabel = [[UILabel alloc]
                              initWithFrame:CGRectMake(pX, pY,
                                                       self.checkCodeNumberLabel.frame.size.width / 4,
                                                       self.checkCodeNumberLabel.frame.size.height)];
        tempLabel.backgroundColor = [UIColor clearColor];
        
        // 字体颜色
        float red = arc4random() % 100 / 100.0;
        float green = arc4random() % 100 / 100.0;
        float blue = arc4random() % 100 / 100.0;
        UIColor *color = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
    
        NSString *textC = [NSString stringWithFormat:@"%C", c];
        tempLabel.textColor = color;
        tempLabel.text = textC;
        [self.checkCodeNumberLabel addSubview:tempLabel];
      }
      
      // 干扰线
      CGContextRef context = UIGraphicsGetCurrentContext();
      CGContextSetLineWidth(context, 1.0);
      for(int i = 0; i < count; i++) {
        red = arc4random() % 100 / 100.0;
        green = arc4random() % 100 / 100.0;
        blue = arc4random() % 100 / 100.0;
        color = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
        CGContextSetStrokeColorWithColor(context, [color CGColor]);
        pX = arc4random() % (int)self.checkCodeNumberLabel.frame.size.width;
        pY = arc4random() % (int)self.checkCodeNumberLabel.frame.size.height;
        CGContextMoveToPoint(context, pX, pY);
        pX = arc4random() % (int)self.checkCodeNumberLabel.frame.size.width;
        pY = arc4random() % (int)self.checkCodeNumberLabel.frame.size.height;
        CGContextAddLineToPoint(context, pX, pY);
        CGContextStrokePath(context);
      }
      return;
    }
    

    展开全文
  • 在开发中注册的时候移动端...完整代码class CodeView: UIView { var changeString:String? //验证码的字符串 let kLineCount = 6 let kLineWidth = CGFloat(2.0) let kCharCount = 4 let kFontSize = UIFont.syst

    在开发中注册的时候移动端要求我们获取随机校码

    完整代码

    class CodeView: UIView {
    
        var changeString:String?  //验证码的字符串
    
        let kLineCount = 6
        let kLineWidth = CGFloat(2.0)
        let kCharCount = 4
        let kFontSize = UIFont.systemFont(ofSize:(CGFloat(arc4random() % 5) + 18))
    
        override init(frame: CGRect) {
            super.init(frame: frame)
    
            let randomColor:UIColor = UIColor(red: CGFloat(CGFloat(arc4random())/CGFloat(RAND_MAX)), green: CGFloat(CGFloat(arc4random())/CGFloat(RAND_MAX)), blue: CGFloat(CGFloat(arc4random())/CGFloat(RAND_MAX)), alpha: 0.5)
    
    //        self.layer.cornerRadius = 5.0   //设置layer圆角半径
    //        self.layer.masksToBounds = true //隐藏边界
            self.backgroundColor = randomColor
    
            getChangeCode()
    
        }
    
    
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
    
        func getChangeCode()
        {
            //字符素材数组
            let changeArray:NSArray = ["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"]
    
            changeString = ""
            //随机从数组中选取需要个数的字符,然后拼接为一个字符串
    
            for _ in 0 ..< kCharCount {
                let index = Int(arc4random())%(changeArray.count - 1)
                let getStr = changeArray.object(at: index)
                changeString = changeString! + (getStr as! String)
            }
    
        }
    
    
        //触摸
        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    
            super.touchesBegan(touches, with: event)
            getChangeCode()
            setNeedsDisplay()
        }
    
    
        //画图
        override func draw(_ rect: CGRect) {
            super.draw(rect)
    
            let randomBackColor = UIColor(red: CGFloat(CGFloat(arc4random())/CGFloat(RAND_MAX)), green: CGFloat(CGFloat(arc4random())/CGFloat(RAND_MAX)), blue: CGFloat(CGFloat(arc4random())/CGFloat(RAND_MAX)), alpha: 1.0)
            self.backgroundColor = randomBackColor
    
            //获得要显示验证码字符串,根据长度,计算每个字符显示的大概位置
            let str = NSString(string: "S")
    
            //        let font = UIFont.systemFontOfSize(20)
            let size = str.size(withAttributes: ([NSAttributedStringKey.font : kFontSize]))
            let width:CGFloat = rect.size.width / CGFloat(NSString(string: changeString!).length) - size.width
            let height = rect.size.height - size.height
            var point:CGPoint?
            var pX:CGFloat?
            var pY:CGFloat?
    
            let stringCount:Int = (changeString?.characters.count)!
    
    
            for i in 0 ..< stringCount {
    
    
                pX = CGFloat(arc4random()).truncatingRemainder(dividingBy: width) + rect.size.width / CGFloat(NSString(string: changeString!).length)*CGFloat(i)
    
                pY = CGFloat(arc4random()).truncatingRemainder(dividingBy: height)
    
    
                point = CGPoint(x:pX!, y:pY!)
    
                let c = NSString(string: changeString!).character(at: i)
    
                let codeText:NSString? = NSString(format: "%C",c)
    
                codeText!.draw(at: point!, withAttributes:  [NSAttributedStringKey.font : kFontSize])
    
            }
    
    
            //调用drawRect:之前,系统会向栈中压入一个CGContextRef,调用UIGraphicsGetCurrentContext()会取栈顶的CGContextRef
            let context :CGContext = UIGraphicsGetCurrentContext()!
            //设置画线宽度
    
            context.setLineWidth(kLineWidth)
    
    
            for _ in 0 ..< kLineCount {
                //绘制干扰的彩色直线
                let randomLineColor = UIColor(red: CGFloat(CGFloat(arc4random())/CGFloat(RAND_MAX)), green: CGFloat(CGFloat(arc4random())/CGFloat(RAND_MAX)), blue: CGFloat(CGFloat(arc4random())/CGFloat(RAND_MAX)), alpha: 0.5)
                context.setStrokeColor(randomLineColor.cgColor)
    
    
                //设置线的起点
                pX = CGFloat(arc4random()).truncatingRemainder(dividingBy: rect.size.width)
                pY = CGFloat(arc4random()).truncatingRemainder(dividingBy: rect.size.height)
                context.move(to: CGPoint(x:pX!, y:pY!))
    
    
                //设置线终点
                pX = CGFloat(arc4random()).truncatingRemainder(dividingBy: rect.size.width)
                pY = CGFloat(arc4random()).truncatingRemainder(dividingBy: rect.size.height)
                context.addLine(to: CGPoint(x:pX!, y:pY!))
                //画线
                context.strokePath()
            }
    
    
        }
    
    
        /*
        // Only override draw() if you perform custom drawing.
        // An empty implementation adversely affects performance during animation.
        override func draw(_ rect: CGRect) {
            // Drawing code
        }
        */
    
    }
    展开全文
  • 生成图形验证码

    2019-06-14 11:47:43
    验证码控制器 package cn.mycs.authenticate.server.controller; import cn.mycs.core.support.StrKit; import cn.mycs.core.util.KaptchaUtil; import cn.mycs.server.persistence.redis.RedisService; import...

    验证码控制器

     

    package cn.mycs.authenticate.server.controller;
    
    import cn.mycs.core.support.StrKit;
    import cn.mycs.core.util.KaptchaUtil;
    import cn.mycs.server.persistence.redis.RedisService;
    import com.google.code.kaptcha.Constants;
    import com.google.code.kaptcha.Producer;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import javax.imageio.ImageIO;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    
    /**
      *<p>验证码控制器</p>
      *
      *<pre>
      * @author gitamacai
      * @date 2018/8/23 9:13
      *</pre>
      */
    @Controller
    public class KaptchaController {
        @Autowired
        private Producer producer;
        @Autowired
        private RedisService redisService;
    
        /**
         * 生成验证码
         */
        @RequestMapping("/validateCode")
        public void validateCode(HttpServletRequest request, HttpServletResponse response) {
            HttpSession session = request.getSession();
    
            response.setDateHeader("Expires", 0);
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
    
            response.setContentType("image/jpeg");
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    
            String capText = producer.createText();
            if (StrKit.isNotEmpty(capText)) {
                //保存到session 
                //session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
                //保存到redis ,有效期为10分钟
                redisService.setByDbIndex(KaptchaUtil.getRedisKey(), capText,KaptchaUtil.KAPTCHA_TTL, KaptchaUtil.DBINDEX);
            }
    
            BufferedImage bi = producer.createImage(capText);
            try (ServletOutputStream out = response.getOutputStream()) {
                ImageIO.write(bi, "jpg", out);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    }
    

     

    备注:

    pom.xml 配置:

    <dependency>
        <groupId>com.github.penggle</groupId>
        <artifactId>kaptcha</artifactId>
    </dependency>

     

    展开全文
  • 本地生成验证码

    2019-06-15 10:11:38
    2019独角兽企业重金招聘Python工程师标准>>> ...
  • Swift虽然是一个新出的语言,但却不提供专门的处理正则的语法和类。所以我们只能使用古老的NSRegularExpression类进行正则匹配。 即先接受一个正则表达式的字符串,由此生成NSRegularExpression对象,再用该对象来...
  • Python如何生成验证码;Python生成网站验证码,python图片处理:绘制 文章出自我的博客:huhansome的博客 上次切图用到了强大的PIL库,这次继续玩一玩PIL。在某些网站经常会看到验证码图片,于是就想到自己写一个看...
  • 在登陆框中,用一个图片控件:  <div id="CheckDiv" runat="server"> <label>验证码:</label> <asp:TextBox ID="tbCode" runat="server"/> ...
  • 昨天看了一篇博文利用阿里云大于平台给手机发送验证码和短信,当时自己就很感兴趣,因为这个技术很有用,相当于以后做用户注册的功能可以进行短信验证,并且大于平台的短信收费也很低,我自己都没有花钱。...
  • Swift4.0入门视频教程,课程内容包含Swift入门知识、数据类型(元组、Dictionary、运算符)、流程控制、函数、类与对象、扩展协议、常见概念、实用进阶、案例实战。 1、119节大容量课程:包含了Swift4.0语言大部分...
  • swift定时器的使用

    2019-08-28 11:02:30
    Swift定时器的使用 在程序开发中,我们常常需要记录定时操作,比如短信验证码倒计时,运动计时等具有时间序列概念的操作。 最常用的定时方式有Timer 和GCD dispatchTimer 一、Timer的使用 Timer类的定义 主要...
  • 本文将介绍WWDC18 Automatic Strong Passwords and Security Code Autofill和WWDC17 Introducing Password AutoFill for Apps中提到的几个功能: 密码自动填充/自动生成的强密码/验证码自动填充等. 如果需要更好的...
  • // qshdVerifyCodeView.swift // qshd // // Created by 钟高荣 on 2020/3/12. // Copyright © 2020 钟高荣. All rights reserved. // import UIKit class qshdVerifyCodeView: UIView { // 验证码的位数 ...
  • 1. app中使用手机号码获取验证码作为登录条件。(与各种电话平台合作,一般价格为 几分 - 1毛不等)  2. 电商app ,实名认证接口。 输入用户姓名与身份证号码进行实名认证 (一般公司都是与其他平台进行合作,基本上...
  • 验证码页面验证

    2020-01-07 21:37:03
    //在全局 定义验证码 function createCode(){ code = ""; var codeLength = 4;//验证码的长度 //所有候选组成验证码的字符,可以用中文 var selectChar = new Array(2,3,4,5,6,7,8,'A','B','C', ...
  • 在这一篇中将讲验证码识别,也就是我们要实现自动化处理的部分。有了前面的知识,这一部分将会变得很容易,下面先说下具体的流程,如下图所示: 1. 将样本库加载到内存  首先需要再回顾下样本库的格式,如下: ...
  • 随机生成图片

    2010-10-04 14:35:00
    只要判断用户输入的数据是否和Session[“Validate”]相等就行了...public partial class 生成随机图片 : System.Web.UI.Page { //生成随机图片背景 protected void CreateImageM(string validateCode) {
  • 这段时间开始研究swift,打算在下个项目上手swift特此整理的常常转载的一些swift常用的第三方的框架。 功能 常用框架 主框架导航 -animated-tab-bar - ESTabBarController - youtube-iOS - ...
  • SWIFT SWIFT是于1973年成立的一个组织,其目的是为了国际银行间的交易保驾护航。该组织成立时候有15个成员国,2008年时已经发展到208个成员国。 银行和银行之间是通过SWIFT来传递交易消息的。而为了确保消息的...
1 2 3 4 5 ... 16
收藏数 309
精华内容 123
热门标签
关键字:

swift 生成验证码