在应用程序注册、登陆或者有关支付确认的界面,经常会用到验证码,验证码有的是通过手机发送获取的,有的是在本地点击获取的,通过手机发送获取的动态验证码可以使用第三方类库实现,本地点击获取的是在本地自己绘制的,下面我们来详细讲解一下本地生成动态验证码的过程。

<一>导入CoreGraphics.framework

<二>验证码封装了一个UIView,在使用的时候直接把这个View加到界面上使用

  CaptchaView.h

#import <UIKit/UIKit.h>@interface CaptchaView : UIView@property (nonatomic, retain) NSArray *changeArray; //字符素材数组
@property (nonatomic, retain) NSMutableString *changeString;  //验证码的字符串@end

  CaptchaView.m

#import "CaptchaView.h"#define kRandomColor  [UIColor colorWithRed:arc4random() % 256 / 256.0 green:arc4random() % 256 / 256.0 blue:arc4random() % 256 / 256.0 alpha:1.0];
#define kLineCount 6
#define kLineWidth 1.0
#define kCharCount 6
#define kFontSize [UIFont systemFontOfSize:arc4random() % 5 + 15]@implementation CaptchaView
@synthesize changeString,changeArray;- (instancetype)initWithFrame:(CGRect)frame
{if (self = [super initWithFrame:frame]) {self.layer.cornerRadius = 5.0; //设置layer圆角半径self.layer.masksToBounds = YES; //隐藏边界self.backgroundColor = kRandomColor;//显示一个随机验证码[self changeCaptcha];}return self;
}
#pragma mark 更换验证码,得到更换的验证码的字符串
-(void)changeCaptcha
{
//<一>从字符数组中随机抽取相应数量的字符,组成验证码字符串//数组中存放的是全部可选的字符,可以是字母,也可以是中文self.changeArray = [[NSArray alloc] initWithObjects:@"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",@"杰",@"瑞",@"教",@"育",nil];//如果能确定最大需要的容量,使用initWithCapacity:来设置,好处是当元素个数不超过容量时,添加元素不需要重新分配内存NSMutableString *getStr = [[NSMutableString alloc] initWithCapacity:kCharCount];self.changeString = [[NSMutableString alloc] initWithCapacity:kCharCount];//随机从数组中选取需要个数的字符,然后拼接为一个字符串for(int i = 0; i < kCharCount; i++){NSInteger index = arc4random() % ([self.changeArray count] - 1);getStr = [self.changeArray objectAtIndex:index];self.changeString = (NSMutableString *)[self.changeString stringByAppendingString:getStr];}//<2>从网络获取字符串,然后把得到的字符串在本地绘制出来(网络获取步骤在这省略)
//    self.changeString = [NSMutableString stringWithString:@"杰瑞教育"];
}#pragma mark 点击view时调用,因为当前类自身就是UIView,点击更换验证码可以直接写到这个方法中,不用再额外添加手势
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{//点击界面,切换验证码[self changeCaptcha];//setNeedsDisplay调用drawRect方法来实现view的绘制[self setNeedsDisplay];
}#pragma mark 绘制界面(1.UIView初始化后自动调用; 2.调用setNeedsDisplay方法时会自动调用)
- (void)drawRect:(CGRect)rect {// 重写父类方法,首先要调用父类的方法[super drawRect:rect];//设置随机背景颜色self.backgroundColor = kRandomColor;//获得要显示验证码字符串,根据长度,计算每个字符显示的大概位置NSString *text = [NSString stringWithFormat:@"%@",self.changeString];CGSize cSize = [@"S" sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20]}];int width = rect.size.width / text.length - cSize.width;int height = rect.size.height - cSize.height;CGPoint point;//依次绘制每一个字符,可以设置显示的每个字符的字体大小、颜色、样式等float pX, pY;for (int i = 0; i < text.length; i++){pX = arc4random() % width + rect.size.width / text.length * i;pY = arc4random() % height;point = CGPointMake(pX, pY);unichar c = [text characterAtIndex:i];NSString *textC = [NSString stringWithFormat:@"%C", c];[textC drawAtPoint:point withAttributes:@{NSFontAttributeName:kFontSize}];}//调用drawRect:之前,系统会向栈中压入一个CGContextRef,调用UIGraphicsGetCurrentContext()会取栈顶的CGContextRefCGContextRef context = UIGraphicsGetCurrentContext();//设置画线宽度CGContextSetLineWidth(context, kLineWidth);//绘制干扰的彩色直线for(int i = 0; i < kLineCount; i++){//设置线的随机颜色UIColor *color = kRandomColor;CGContextSetStrokeColorWithColor(context, [color CGColor]);//设置线的起点pX = arc4random() % (int)rect.size.width;pY = arc4random() % (int)rect.size.height;CGContextMoveToPoint(context, pX, pY);//设置线终点pX = arc4random() % (int)rect.size.width;pY = arc4random() % (int)rect.size.height;CGContextAddLineToPoint(context, pX, pY);//画线CGContextStrokePath(context);}
}@end

<三>在界面上添加验证码

   ViewController.m

#import "ViewController.h"
#import "CaptchaView.h"@interface ViewController ()<UITextFieldDelegate,UIAlertViewDelegate>
{CaptchaView *_captchaView;UITextField *_input;
}@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];//显示验证码界面_captchaView = [[CaptchaView alloc] initWithFrame:CGRectMake(20, 40, 150, 40)];[self.view addSubview:_captchaView];//提示文字UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(190, 40, 100, 40)];label.text = @"点击图片换验证码";label.font = [UIFont systemFontOfSize:12];label.textColor = [UIColor grayColor];[self.view addSubview:label];//添加输入框_input = [[UITextField alloc] initWithFrame:CGRectMake(20, 100, 150, 40)];_input.layer.borderColor = [UIColor lightGrayColor].CGColor;_input.layer.borderWidth = 2.0;_input.layer.cornerRadius = 5.0;_input.font = [UIFont systemFontOfSize:21];_input.placeholder = @"请输入验证码!";_input.clearButtonMode = UITextFieldViewModeWhileEditing;_input.backgroundColor = [UIColor clearColor];_input.textAlignment = NSTextAlignmentCenter;_input.returnKeyType = UIReturnKeyDone;_input.delegate = self;[self.view addSubview:_input];
}#pragma mark 输入框协议中方法,点击return按钮
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{//判断输入的是否为验证图片显示的验证码if ([_input.text isEqualToString:_captchaView.changeString]) {//正确弹出警告款提示正确UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"恭喜您 ^o^" message:@"验证成功" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];[alview show];}else{//验证不匹配,验证码和输入框晃动CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.x"];anim.repeatCount = 1;anim.values = @[@-20, @20, @-20];[_captchaView.layer addAnimation:anim forKey:nil];[_input.layer addAnimation:anim forKey:nil];}return YES;
}#pragma mark 警告框中方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{//清空输入框内容,收回键盘if (buttonIndex==0) {_input.text = @"";[_input resignFirstResponder];}
}
@end

  想要了解更多内容的小伙伴,可以点击查看源码,亲自运行测试。

作者: 杰瑞教育
出处: http://blog.csdn.net/jerehedu
本文版权归烟台杰瑞教育科技有限公司和CSDN共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

IOS 生成本地验证码相关推荐

  1. iOS 生成本地验证码以及使用

    #import <UIKit/UIKit.h> @interface CaptchaView : UIView @property (nonatomic, retain) NSArray ...

  2. python随机生成验证码_Python生成随机验证码

    #生成随机验证码 from PIL importImagefrom io importBytesIOfrom PIL importImageDraw,ImageFontdefcheck_code(re ...

  3. hbuildx打包成apk_HBuilderX生成本地打包App资源

    概要 在HBuilderX中开发的应用可以提交到云端打包生成apk(Android平台)和ipa(iOS平台). 如果本地配置好对应的原生开发环境,也可以使用本地打包 生成App资源 选中需要打包项目 ...

  4. 使用wsimport生成本地调用代码

    使用wsimport生成本地调用的步骤 wsimport是jdk自带的,可以根据wsdl文档生成客户端调用代码的工具. wsimport.exe位于JAVA_HOME\bin目录下. 常用参数为: - ...

  5. iOS 生成二维码/条形码

    级别:★★☆☆☆ 标签:「iOS CIFilter」「CIQRCodeGenerator」「CICode128BarcodeGenerator」「二维码加logo」 作者: Xs·H 审校: QiSh ...

  6. php怎样验证验证码对错,PHP生成中文验证码并检测对错实例

    PHP生成中文验证码并检测对错实例,中文验证码的例子还是比较少的,今天给大家分享一下,支持自定义中文.字体.背景色等 生成验证码,注意font字体路径要对,否则显示图片不存在session_start ...

  7. iOS实现本地通知(local notification)的方法

    iOS 的本地通知(local notification)用于基于时间行为的通知,比如有关日历或者 todo 列表的小应用.另外应用如果在后台执行,iOS 允许它在受限的时间内运 行,它也会发现本地通 ...

  8. python输入ip地址_python批量生成本地ip地址的方法

    本文实例讲述了python批量生成本地ip地址的方法.分享给大家供大家参考.具体分析如下: 这段代码用于在本地计算机上生成本地ip地址绑定到网卡,生成的是一个bat的批处理文件,运行此批处理文件,可以 ...

  9. python编程实战(二):一文教你生成随机验证码!大小写字母与数字组合,位数可以控制

    随机验证码的生成 前言 正文 实现 代码 效果 前言 验证码验证,是常见的安全验证的一种方式,可以用来杜绝脚本和机器人操作等等: 除了本文介绍的简单的验证码之外,还有拼图验证.文字顺序验证等常见的验证 ...

最新文章

  1. WordCount扩展与优化
  2. 进阶学习(3.2)Factory Method Pattern 工厂方法模式
  3. 最新开源JavaScript 图表库 ECharts推荐
  4. C# winfrom listView
  5. python文件和数据的格式化_Python在文本文件中格式化特定数据
  6. python str方法的用法_Python基础之str常用方法、for循环
  7. 使用soap遇到的缓存问题
  8. 【uniapp 课程表】
  9. tortoise介绍
  10. Linux文件颜色所代表的含义
  11. Android 自定义心形图片
  12. 请控制好你的情绪--职场情绪管理
  13. adobe illustrator 绘制平行四边形
  14. 4.19 使用QT做上位机与下位机通讯
  15. Centos7 编译安装git 报错 git-compat-util.h:14:2: error
  16. 玩转安卓 Android系统文件夹结构解析(绝对有用)
  17. 8、 高德离线地图开发教程
  18. 视频面试前这些准备工作,你做对了吗?
  19. jspsmartupload用法
  20. qemu声卡模拟原理-声音播放(pa+ac97)

热门文章

  1. PMP考试经验总结分享
  2. 如何写一个简单的局域网游戏
  3. STC89C52单片机数码管介绍以及代码示例
  4. Arm内核的Oops错误定位方法
  5. 深度学习之细粒度分类
  6. 计算机技术 高中教案,高中信息技术 计算机软件教案
  7. 计算机技术 食堂管理,食堂管理系统需求规格说明.doc
  8. 磁盘分区克隆:操作系统迁移工具更换硬盘怎么操作?
  9. 零基础过五门CPA的一些经验及教训分享
  10. 利用ant编译EJB(1)-生成公共包