IOS 生成本地验证码
下载源码连接
链接: http://pan.baidu.com/s/1bnxwMmz 密码: j3yn
在应用程序注册、登陆或者有关支付确认的界面,经常会用到验证码,验证码有的是通过手机发送获取的,有的是在本地点击获取的,通过手机发送获取的动态验证码可以使用第三方类库实现,本地点击获取的是在本地自己绘制的,下面我们来详细讲解一下本地生成动态验证码的过程。
<一>导入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++