項目中有時候會有這種需求: 獲取這種 隨機字符組成的圖片驗證碼.html
隨機字符組成的圖片驗證碼, 字符位數可改變, 字符可斜可正排列.dom
1.初始化驗證碼的背景且設置隨機色測試
2.獲取驗證圖上的字符碼並經過bolck帶回驗證碼值3d
3.在背景上添加標籤,獲取字符隨機產生賦值給標籤(可斜可正排列)code
4.添加干擾線於背景orm
5.初始化添加驗證碼視圖 並添加手勢點擊刷新htm
6.判斷驗證碼字符是否輸入正確(區分大小寫)blog
首先 初始化建立驗證碼背景:ZLSecurityCodeImgView, 最後初始化添加驗證碼視圖並添加手勢點擊刷新.圖片
一、初始化驗證碼的背景且設置隨機色rem
初始化背景:
if (_bgView) { [_bgView removeFromSuperview]; } _bgView = [[UIView alloc]initWithFrame:self.bounds]; [self addSubview:_bgView]; [_bgView setBackgroundColor:[self getRandomBgColorWithAlpha:0.5]];
產生背景隨機色:
- (UIColor *)getRandomBgColorWithAlpha:(CGFloat)alpha { float red = arc4random() % 100 / 100.0; float green = arc4random() % 100 / 100.0; float blue = arc4random() % 100 / 100.0; UIColor *color = [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; return color; }
二、獲取驗證圖上的字符碼並經過bolck帶回驗證碼值
- (void)changeCodeStr { // 目前是數字字母 self.textArr = [[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]; for(NSInteger i = 0; i < CodeCount; i++) { NSInteger index = arc4random() % ([self.textArr count] - 1); NSString *oneText = [self.textArr objectAtIndex:index]; self.imageCodeStr = (i==0) ? oneText : [self.imageCodeStr stringByAppendingString:oneText]; } // block 塊帶回驗證碼值 if (self.bolck) { self.bolck(self.imageCodeStr); } }
其中這個字符CodeCount的個數能夠按照本身需求了來修改.
四位斜驗證碼:
5位斜字符驗證碼:
三、在背景上添加標籤,獲取字符隨機產生賦值給標籤(可斜可正排列)
for (int i = 0; i<self.imageCodeStr.length; i++) { CGFloat px = arc4random()%randWidth + i*(self.frame.size.width-3)/self.imageCodeStr.length; CGFloat py = arc4random()%randHeight; UILabel * label = [[UILabel alloc] initWithFrame: CGRectMake(px+3, py, textSize.width, textSize.height)]; label.text = [NSString stringWithFormat:@"%C", [self.imageCodeStr characterAtIndex:i]]; label.font = [UIFont systemFontOfSize:20]; if (self.isRotation) { // 驗證碼字符是否須要斜着 double r = (double)arc4random() / ARC4RAND_MAX * 2 - 1.0f; // 隨機-1到1 if (r > 0.3) { r = 0.3; }else if(r < -0.3){ r = -0.3; } label.transform = CGAffineTransformMakeRotation(r); } [_bgView addSubview:label]; }
其中這個字符的正斜能夠按照本身需求了來修改,這裏看下正的:
四、添加干擾線於背景
for (int i = 0; i<10; i++) { UIBezierPath *path = [UIBezierPath bezierPath]; CGFloat pX = arc4random() % (int)CGRectGetWidth(self.frame); CGFloat pY = arc4random() % (int)CGRectGetHeight(self.frame); [path moveToPoint:CGPointMake(pX, pY)]; CGFloat ptX = arc4random() % (int)CGRectGetWidth(self.frame); CGFloat ptY = arc4random() % (int)CGRectGetHeight(self.frame); [path addLineToPoint:CGPointMake(ptX, ptY)]; CAShapeLayer *layer = [CAShapeLayer layer]; layer.strokeColor = [[self getRandomBgColorWithAlpha:0.2] CGColor]; // layer的邊框色 layer.lineWidth = 1.0f; layer.strokeEnd = 1; layer.fillColor = [UIColor clearColor].CGColor; layer.path = path.CGPath; [_bgView.layer addSublayer:layer]; }
五、初始化添加驗證碼視圖 並添加手勢點擊刷新
初始化添加驗證碼視圖:
- (void)setupSecurityCodeImgView { // 驗證碼背景寬高可根據需求自定義 _codeImgView = [[ZLSecurityCodeImgView alloc] initWithFrame:CGRectMake(150, 200, 100, 40)]; _codeImgView.bolck = ^(NSString *imageCodeStr){ // 根據需求是否使用驗證碼值 // 打印生成的驗證碼 NSLog(@"imageCodeStr = %@", imageCodeStr); }; // 驗證碼字符是否須要斜着 _codeImgView.isRotation = YES; [_codeImgView refreshSecurityCode]; [self.view addSubview: _codeImgView]; }
添加手勢點擊刷新:
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)]; [_codeImgView addGestureRecognizer:tap];
- (void)tapClick:(UITapGestureRecognizer *)tap { [_codeImgView refreshSecurityCode]; }
斜驗證碼圖刷新運行效果:
六、判斷驗證碼字符是否輸入正確(區分大小寫)
#pragma mark- UITextFieldDelegate - (BOOL)textFieldShouldReturn:(UITextField *)textField { if (textField == self.codeField) { [self.codeField resignFirstResponder]; // 判斷驗證碼字符是否輸入正確(區分大小寫) if ([textField.text isEqualToString:self.imageCodeStr]) { UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"測試" message:@"匹配成功" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"肯定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { }]; [alert addAction:okAction]; [self presentViewController:alert animated:YES completion:nil]; } else { UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"測試" message:@"匹配失敗" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"肯定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { }]; [alert addAction:okAction]; [self presentViewController:alert animated:YES completion:nil]; } } return YES; }
這時候總體測試一下效果 :
一、壓縮文件截圖:
界面性問題能夠根據本身項目需求調整便可, 具體可參考代碼, 項目則可以直接運行!