iOS 生成本地驗證碼
在應用程序注冊、登陸或者有關支付確認的界面,經常會用到驗證碼,驗證碼有的是通過手機發送獲取的,有的是在本地點擊獲取的,通過手機發送獲取的動態驗證碼可以使用第三方類庫實現,本地點擊獲取的是在本地自己繪制的,下面我們來詳細講解一下本地生成動態驗證碼的過程。
導入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()會取棧頂的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);
//畫線
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 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!