混淆的驗證碼視圖,是我們?nèi)粘=?jīng)常用到的功能模塊之一,一般來說后臺不會直接返回我們驗證碼的圖片,一般需要我們將字符串信息轉換成我們需要的視圖;不管是轉換成View還是button,這里介紹一個比較簡單的方法,重寫
- (void)drawRect:(CGRect)rect
這里一般需要兩個步驟,一是重寫字符串的字體大小、顏色、樣式等
首先計算每個字符顯示的位置
NSString *text = [NSString stringWithFormat:@"%@", self.verifyCode];
CGSize cSize = [@"A" sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20]}];
int width = rect.size.width/text.length - cSize.width;
int height = rect.size.height - cSize.height;
設置字符串的字體大小、顏色
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];
UIFont *randomFont = [UIFont systemFontOfSize:arc4random() % 5 + 15];
[textC drawAtPoint:point withAttributes:@{NSFontAttributeName : randomFont}];
}
當然這樣還是完全不夠的,還需要我們繪制干擾線
CGContextRef context = UIGraphicsGetCurrentContext();
//設置線條寬度
CGContextSetLineWidth(context, kLineWidth);
//繪制干擾線
for (int i = 0; i < kLineCount; i++)
{
UIColor *randomColor = [UIColor colorWithRed:arc4random() % 256 / 256.0 green:arc4random() % 256 / 256.0 blue:arc4random() % 256 / 256.0 alpha:1.0];
CGContextSetStrokeColorWithColor(context, randomColor.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);
}