利用Quartz2D實(shí)現(xiàn):
繪圖步驟: 1.獲取上下文 2.描述路徑 3.把路徑添加到上下文 4.渲染上下文
drawRect:畫(huà)線必須要在drawRect方法實(shí)現(xiàn)担汤,因?yàn)橹挥性赿rawRect方法中才能獲取到根view相關(guān)聯(lián)上下文歉糜;當(dāng)前控件即將顯示的時(shí)候調(diào)用壳贪,只調(diào)用一次咒精;
注意:
drawRect不能手動(dòng)調(diào)用锌钮;drawRect只能系統(tǒng)調(diào)用,每次系統(tǒng)調(diào)用drawRect方法之前,都會(huì)給drawRect方法傳遞一個(gè)跟當(dāng)前view相關(guān)聯(lián)上下文陨闹;
執(zhí)行[self.view setNeedsDisplay];
會(huì)調(diào)用drawRect樟凄。
效果圖
#define kRandomColor [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1.0] //隨機(jī)顏色
#define kLineCount 6 //干擾線的個(gè)數(shù)
#define kLineWidth 1.0 //干擾線的寬度
#define kCharCount 5 //需要驗(yàn)證碼的個(gè)數(shù)
#define kFontSize [UIFont systemFontOfSize:arc4random() % 5 + 15] //字體大小
獲取隨機(jī)驗(yàn)證碼
#pragma mark - 獲取隨機(jī)驗(yàn)證碼
- (void)getAuthcode {
_authCodeStr = [[NSMutableString alloc] initWithCapacity:kCharCount];
_dataArray = @[@1,@2,@4,@5,@7,@8,@0,@9,@"Z",@"W",@"E",@"R",@"L",@"w",@"g",@"j",@"t",@"v"];
//隨機(jī)從素材數(shù)組中取出需要個(gè)數(shù)的字符串聘芜,拼接為驗(yàn)證碼字符串存入驗(yàn)證碼數(shù)組中
for (int i = 0; i < kCharCount; i ++){
NSInteger index = arc4random() % self.dataArray.count;
[self.authCodeStr insertString:[NSString stringWithFormat:@"%@",self.dataArray[index]] atIndex:i];
}
}
點(diǎn)擊view刷新驗(yàn)證碼
//點(diǎn)擊界面切換驗(yàn)證碼
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[self getAuthcode];
[self setNeedsDisplay];
}
繪制驗(yàn)證碼和線條
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
self.backgroundColor = [UIColor whiteColor];
/*計(jì)算每個(gè)字符串顯示的位置*/
NSString *text = [NSString stringWithFormat:@"%@",_authCodeStr];
CGSize cSize = [@"A" sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20]}];
int width = rect.size.width / text.length - cSize.width;
int height = rect.size.height - cSize.height;
CGPoint point;
/*繪制字符*/
float tempX,tempY;
for (int i = 0 ; i < text.length; i ++) {
tempX = arc4random() % width + rect.size.width / text.length * i;
tempY = arc4random() % height;
point = CGPointMake(tempX, tempY);
unichar c = [text characterAtIndex:i];
NSString *textC = [NSString stringWithFormat:@"%C", c];
[textC drawAtPoint:point withAttributes:@{NSFontAttributeName:kFontSize}];
}
//繪制kLineCount條隨機(jī)色干擾線
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context,kLineWidth);
for(int cout = 0; cout < kLineCount; cout++)
{
CGContextSetStrokeColorWithColor(context, kRandomColor.CGColor);
tempX = arc4random() % (int)rect.size.width;
tempY = arc4random() % (int)rect.size.height;
CGContextMoveToPoint(context, tempX, tempY);
tempX = arc4random() % (int)rect.size.width;
tempY = arc4random() % (int)rect.size.height;
CGContextAddLineToPoint(context, tempX, tempY);
CGContextStrokePath(context);
}
}