我在菜鳥系列里講過我們可以使用UIKit和CoreGraphics繪制圖片和文字悯周,這里就簡單的講一下在app中很常見的地方:圖形文字驗(yàn)證碼的繪制改含。
講到圖形驗(yàn)證碼绝页,顧名思義晃虫,就是在注冊或者登錄的時候皆撩,系統(tǒng)會彈出幾個文字或者字母數(shù)字供我們選擇,這一方面可以驗(yàn)證操作的真實(shí)性傲茄,另一方面也可以防止不法分子域名攻擊毅访。
效果如:
按照往常的習(xí)慣,先貼github地址盘榨,因?yàn)榇a其實(shí)很簡單,相信看一下代碼就明白了蟆融,喜歡的賞顆星星
不過我還是想嘮叨兩句草巡,不然代碼不是白寫了。型酥。山憨。。弥喉。郁竟。
跟圖形繪制一樣,我們在自定義空間GraphCodeView的- (void)drawRect:(CGRect)rect由境;方法中截取出文字棚亩,然后對文字進(jìn)行繪制操作,再添加兩條干擾線虏杰。
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;
上面這兩句代碼無非就是根據(jù)字號獲取等分字符之間的間距
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]}];
通過上面的方法隨機(jī)獲取繪制文字的坐標(biāo)讥蟆,這樣看起來達(dá)到繪制文字參差不齊的效果
最后就是繪制干擾線的操作了
//繪制干擾線
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);//設(shè)置線條填充色
//設(shè)置線的起點(diǎn)
pX = arc4random() % (int)rect.size.width;
pY = arc4random() % (int)rect.size.height;
CGContextMoveToPoint(context, pX, pY);
//設(shè)置線終點(diǎn)
pX = arc4random() % (int)rect.size.width;
pY = arc4random() % (int)rect.size.height;
CGContextAddLineToPoint(context, pX, pY);
//畫線
CGContextStrokePath(context);
}
這里要注意一點(diǎn),字符串的獲取我是定義了NSString+random分類纺阔,添加了隨機(jī)獲取字符串的方法
+(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;
}
當(dāng)然這里如果有特定需求也可以從后臺那里拿瘸彤,繪制步驟還是不變的;
區(qū)分大小寫的不同操作如下笛钝,按照需要選擇质况。
//? ? 不區(qū)分大小寫
BOOL result = [_str compare:_codeTextField.text
options:NSCaseInsensitiveSearch |NSNumericSearch] == NSOrderedSame;
// 區(qū)分大小寫
BOOL result2 = [_str isEqualToString:_codeTextField.text];
如果需要重新獲取驗(yàn)證字符,則只需要重繪即可玻靡,如下结榄。
[_graphCodeView setCodeStr:_str];
[_graphCodeView setNeedsDisplay];