本地生成随机验证码,直接上图:
其实逻辑上没什么难度,本地资源库中随机生成指定个数的元素,计算位置方法到指定的画布上显示,添加一些干扰项目即可。最后通过对比输入字符与随机生成的字符串是否相等判断验证结果:下面附上代码。
封装一个基于UIView的类,在需要调用的地方直接使用即可:
.h
#import@interface GALCaptcha : UIView
@property (nonatomic, retain)NSArray *CatArray;//验证码素材库
@property (nonatomic, retain)NSMutableString *CatString;//验证码字符串
@end
//
// GALCaptcha.m
// APPLaunchScreen
//
// Created by love on 2016/11/25.
// Copyright © 2016年 love. All rights reserved.
//
#import "GALCaptcha.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 GALCaptcha
-(instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
self.layer.cornerRadius = 5.0;
self.layer.masksToBounds = YES;
self.backgroundColor = [UIColor greenColor];
//显示一个随机验证码
[self showCaptcha];
}
return self;
}
-(void)showCaptcha
{
//从字符数组中随机抽取相应数量的字符,组成验证码字符串
//数组中存放的是全部可选的字符,可以是字母,也可以是中文
self.CatArray = [[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.CatString = [[NSMutableString alloc] initWithCapacity:kCharCount];
//随机从数组中选取需要个数的字符,然后拼接为一个字符串
for(int i = 0; i < kCharCount; i++)
{
NSInteger index = arc4random() % ([self.CatArray count] - 1);
getStr = [self.CatArray objectAtIndex:index];
self.CatString = (NSMutableString *)[self.CatString stringByAppendingString:getStr];
}
}
#pragma mark 点击view时调用,因为当前类自身就是UIView,点击更换验证码可以直接写到这个方法中,不用再额外添加手势
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//点击界面,切换验证码
[self showCaptcha];
//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.CatString];
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()会取栈顶的CGContextRef
CGContextRef 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);
// //设置线条起点和终点的样式为圆角
// CGContextSetLineCap(context, kCGLineCapRound);
// //设置线条的转角的样式为圆角
// CGContextSetLineJoin(context, kCGLineJoinRound);
//画线
CGContextStrokePath(context);
}
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
@end
在需要使用的类直接导入头文件:
#import "GALCaptcha.h"//加载验证码
@interface ViewController ()<UITextFieldDelegate,UIAlertViewDelegate>
{
GALCaptcha * galCaptcha;
UITextField * _input;
}
@end
使用:
- (void)viewDidLoad {
[super viewDidLoad];
//显示验证码界面
galCaptcha = [[GALCaptcha alloc] initWithFrame:CGRectMake(40, 70, 150, 40)];
[self.view addSubview:galCaptcha];
//提示文字
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(210, 70, 100, 40)];
label.text = @"点击图片换验证码";
label.font = [UIFont systemFontOfSize:12];
label.textColor = [UIColor grayColor];
[self.view addSubview:label];
//添加输入框
_input = [[UITextField alloc] initWithFrame:CGRectMake(40, 130, 150, 40)];
_input.layer.borderColor = [UIColor lightGrayColor].CGColor;
_input.layer.borderWidth = 1.0;
_input.layer.cornerRadius = 5.0;
_input.font = [UIFont systemFontOfSize:18];
_input.placeholder = @"请输入验证码.";
_input.clearButtonMode = UITextFieldViewModeWhileEditing;
_input.backgroundColor = [UIColor clearColor];
_input.textAlignment = NSTextAlignmentCenter;
_input.returnKeyType = UIReturnKeyDone;
_input.delegate = self;
[self.view addSubview:_input];
// Do any additional setup after loading the view, typically from a nib.
}
在键盘的代理方法中做判断或自定义验证方法即可
#pragma mark 输入框协议中方法,点击return按钮
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
//验证码比较应该不区分大小写
int result = [_input.text compare:galCaptcha.CatString options:NSCaseInsensitiveSearch];
NSLog(@"%d",result);
//正确弹出警告款提示正确
if (result == 0) {
UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"恭喜您 ^o^" message:@"验证成功" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alview show];
}else
{
// UIAlertView *alview = [[UIAlertView alloc] initWithTitle:nil message:@"验证失败" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
// [alview show];
//验证不匹配,验证码和输入框晃动
CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.x"];
anim.repeatCount = 1;
anim.values = @[@-20, @20, @-20];
[galCaptcha.layer addAnimation:anim forKey:nil];
[_input.layer addAnimation:anim forKey:nil];
}
// //判断输入的是否为验证图片显示的验证码
// if ([_input.text isEqualToString:galCaptcha.CatString]) {
// //正确弹出警告款提示正确
// 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];
// [galCaptcha.layer addAnimation:anim forKey:nil];
// [_input.layer addAnimation:anim forKey:nil];
// }
return YES;
}
注意: 在验证输入字符与本地生成验证码时不能用 isEqualToString(如果比较式需要区分大小写则可以使用!) 附一份常用字符串比较方式:http://blog.sina.com.cn/s/blog_916e0cff0102uyz1.html