在 iOS 開(kāi)發(fā)中,為了防止短信驗(yàn)證碼的惡意獲取,注冊(cè)時(shí)需要圖片驗(yàn)證,比如某共享單車(chē) APP 在注冊(cè)時(shí)就用了圖片驗(yàn)證碼,如下圖:

-
圖片驗(yàn)證碼封裝思路:
第一眼看到圖片驗(yàn)證碼,可能會(huì)覺(jué)得圖片驗(yàn)證碼是由 UIImage 實(shí)現(xiàn)的,但事實(shí)上明顯不是,這里簡(jiǎn)單說(shuō)下圖片驗(yàn)證碼封裝思路。- 首先要有一個(gè)數(shù)組,里面包含 1-9、a-z 這些字符
- 在 UIView 上顯示這些字符
- 同時(shí)在 UIView 上繪制干擾線
效果圖

圖片驗(yàn)證碼效果圖
- 用法
_testView = [[NNValidationView alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 100) / 2, 200, 100, 40) andCharCount:4 andLineCount:4];
[self.view addSubview:_testView];
以上兩行代碼便可以實(shí)現(xiàn)圖片驗(yàn)證碼,其中 charCount 和 lineCount 分別指顯示的字符串?dāng)?shù)量以及干擾線的數(shù)量。
另外我們還需要知道圖片驗(yàn)證碼上的字符串,可以用下邊這個(gè) block 獲?。?/strong>
__weak typeof(self) weakSelf = self;
/// 返回驗(yàn)證碼數(shù)字
_testView.changeValidationCodeBlock = ^(void){
NSLog(@"驗(yàn)證碼被點(diǎn)擊了:%@", weakSelf.testView.charString);
};
打印效果如下

獲取驗(yàn)證碼數(shù)字
- 核心代碼
#pragma mark - 繪制界面
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
self.backgroundColor = NNRandomColor;
CGFloat rectWidth = rect.size.width;
CGFloat rectHeight = rect.size.height;
CGFloat pointX, pointY;
NSString *text = [NSString stringWithFormat:@"%@",self.charString];
NSInteger charWidth = rectWidth / text.length - 15;
NSInteger charHeight = rectHeight - 25;
// 依次繪制文字
for (NSInteger i = 0; i < text.length; i++) {
// 文字X坐標(biāo)
pointX = arc4random() % charWidth + rectWidth / text.length * i;
// 文字Y坐標(biāo)
pointY = arc4random() % charHeight;
unichar charC = [text characterAtIndex:i];
NSString *textC = [NSString stringWithFormat:@"%C", charC];
[textC drawAtPoint:CGPointMake(pointX, pointY) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:arc4random() % 10 + 15]}];
}
// 獲取上下文
CGContextRef context = UIGraphicsGetCurrentContext();
// 設(shè)置線寬
CGContextSetLineWidth(context, 1.0);
// 依次繪制直線
for(NSInteger i = 0; i < self.lineCount; i++) {
// 設(shè)置線的顏色
CGContextSetStrokeColorWithColor(context, NNRandomColor.CGColor);
// 設(shè)置線的起點(diǎn)
pointX = arc4random() % (NSInteger)rectWidth;
pointY = arc4random() % (NSInteger)rectHeight;
CGContextMoveToPoint(context, pointX, pointY);
// 設(shè)置線的終點(diǎn)
pointX = arc4random() % (NSInteger)rectWidth;
pointY = arc4random() % (NSInteger)rectHeight;
CGContextAddLineToPoint(context, pointX, pointY);
// 繪畫(huà)路徑
CGContextStrokePath(context);
}
}
代碼中寫(xiě)了注釋,因此這里不再詳細(xì)解釋,需要看全部代碼的童鞋可以點(diǎn)擊下邊的鏈接,有疑問(wèn)或有建議的話歡迎討論。