我在菜鳥系列里講過我們可以使用UIKit和CoreGraphics繪制圖片和文字,這里就簡單的講一下在app中很常見的地方:圖形文字驗證碼的繪制。
講到圖形驗證碼,顧名思義,就是在注冊或者登錄的時候,系統會彈出幾個文字或者字母數字供我們選擇,這一方面可以驗證操作的真實性,另一方面也可以防止不法分子域名攻擊。
效果如:
按照往常的習慣,先貼github地址,因為代碼其實很簡單,相信看一下代碼就明白了,喜歡的賞顆星星
不過我還是想嘮叨兩句,不然代碼不是白寫了。。。。。。
跟圖形繪制一樣,我們在自定義空間GraphCodeView的- (void)drawRect:(CGRect)rect;方法中截取出文字,然后對文字進行繪制操作,再添加兩條干擾線。
NSString *text = [NSString stringWithFormat:@"%@",_codeStr];
CGSize cSize = [@"A" sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20]}];
int width = rect.size.width/text.length - cSize.width;
int height = rect.size.height - cSize.height;
上面這兩句代碼無非就是根據字號獲取等分字符之間的間距
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:[UIFont systemFontOfSize:15.0]}];
通過上面的方法隨機獲取繪制文字的坐標,這樣看起來達到繪制文字參差不齊的效果
最后就是繪制干擾線的操作了
//繪制干擾線
for (int i = 0; i < 2; i++)
{
UIColor *color=[UIColor colorWithRed:arc4random() % 256 / 256.0 green:arc4random() % 256 / 256.0 blue:arc4random() % 256 / 256.0 alpha:1.0];
;
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);
}
這里要注意一點,字符串的獲取我是定義了NSString+random分類,添加了隨機獲取字符串的方法
+(NSString *)randomStringWithLength:(NSInteger)len {
NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
NSMutableString *randomString = [NSMutableString stringWithCapacity: len];
for (NSInteger i = 0; i < len; i++) {
[randomString appendFormat: @"%C", [letters characterAtIndex: arc4random_uniform([letters length])]];
}
return randomString;
}
當然這里如果有特定需求也可以從后臺那里拿,繪制步驟還是不變的;
區分大小寫的不同操作如下,按照需要選擇。
//? ? 不區分大小寫
BOOL result = [_str compare:_codeTextField.text
options:NSCaseInsensitiveSearch |NSNumericSearch] == NSOrderedSame;
// 區分大小寫
BOOL result2 = [_str isEqualToString:_codeTextField.text];
如果需要重新獲取驗證字符,則只需要重繪即可,如下。
[_graphCodeView setCodeStr:_str];
[_graphCodeView setNeedsDisplay];