欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS开发实现随机图片验证码封装

程序员文章站 2023-12-18 20:29:22
在 ios 开发中,为了防止短信验证码的恶意获取,注册时需要图片验证,比如某共享单车 app 在注册时就用了图片验证码,如下图: 图片验证码封装思路: 第一眼看...

在 ios 开发中,为了防止短信验证码的恶意获取,注册时需要图片验证,比如某共享单车 app 在注册时就用了图片验证码,如下图:

iOS开发实现随机图片验证码封装

图片验证码封装思路:

第一眼看到图片验证码,可能会觉得图片验证码是由 uiimage 实现的,但事实上明显不是,这里简单说下图片验证码封装思路。

  1. 首先要有一个数组,里面包含 1-9、a-z 这些字符
  2. 在 uiview 上显示这些字符
  3. 同时在 uiview 上绘制干扰线

效果图

iOS开发实现随机图片验证码封装

图片验证码效果图

用法

  _testview = [[nnvalidationview alloc] initwithframe:cgrectmake((self.view.frame.size.width - 100) / 2, 200, 100, 40) andcharcount:4 andlinecount:4];
  [self.view addsubview:_testview];

以上两行代码便可以实现图片验证码,其中 charcount 和 linecount 分别指显示的字符串数量以及干扰线的数量。

另外我们还需要知道图片验证码上的字符串,可以用下边这个 block 获取:

 __weak typeof(self) weakself = self;
  /// 返回验证码数字
  _testview.changevalidationcodeblock = ^(void){
    nslog(@"验证码被点击了:%@", weakself.testview.charstring);
  };

打印效果如下

iOS开发实现随机图片验证码封装

获取验证码数字

核心代码

#pragma mark - 绘制界面
- (void)drawrect:(cgrect)rect {
  [super drawrect:rect];
  self.backgroundcolor = nnrandomcolor;
  cgfloat rectwidth = rect.size.width;
  cgfloat rectheight = rect.size.height;
  cgfloat pointx, pointy;
  
  nsstring *text = [nsstring stringwithformat:@"%@",self.charstring];
  nsinteger charwidth = rectwidth / text.length - 15;
  nsinteger charheight = rectheight - 25;
  
  // 依次绘制文字
  for (nsinteger i = 0; i < text.length; i++) {
    // 文字x坐标
    pointx = arc4random() % charwidth + rectwidth / text.length * i;
    // 文字y坐标
    pointy = arc4random() % charheight;
    unichar charc = [text characteratindex:i];
    nsstring *textc = [nsstring stringwithformat:@"%c", charc];

    [textc drawatpoint:cgpointmake(pointx, pointy) withattributes:@{nsfontattributename:[uifont systemfontofsize:arc4random() % 10 + 15]}];
  }
  
  // 获取上下文
  cgcontextref context = uigraphicsgetcurrentcontext();
  // 设置线宽
  cgcontextsetlinewidth(context, 1.0);
  
  // 依次绘制直线
  for(nsinteger i = 0; i < self.linecount; i++) {
    // 设置线的颜色
    cgcontextsetstrokecolorwithcolor(context, nnrandomcolor.cgcolor);
    // 设置线的起点
    pointx = arc4random() % (nsinteger)rectwidth;
    pointy = arc4random() % (nsinteger)rectheight;
    cgcontextmovetopoint(context, pointx, pointy);
    // 设置线的终点
    pointx = arc4random() % (nsinteger)rectwidth;
    pointy = arc4random() % (nsinteger)rectheight;
    cgcontextaddlinetopoint(context, pointx, pointy);
    // 绘画路径
    cgcontextstrokepath(context);
  }
}

代码中写了注释,因此这里不再详细解释,需要看全部代码的童鞋可以点击下边的链接,有疑问或有建议的话欢迎讨论。

demo 地址:nnvalidationview

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: