IOS 產生本地驗證碼

來源:互聯網
上載者:User

IOS 產生本地驗證碼

  在應用程式註冊、登陸或者有關支付確認的介面,經常會用到驗證碼,驗證碼有的是通過手機發送擷取的,有的是在本地點擊擷取的,通過手機發送擷取的動態驗證碼可以使用第三方類庫實現,本地點擊擷取的是在本地自己繪製的,下面我們來詳細講解一下本地產生動態驗證碼的過程。

<一>匯入CoreGraphics.framework

<二>驗證碼封裝了一個UIView,在使用的時候直接把這個View加到介面上使用

  CaptchaView.h


#import  @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 () { 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

 

  想要瞭解更多內容的小夥伴,可以點擊查看源碼,親自運行測試。

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.