利用Quartz2D實現:
繪圖步驟: 1.獲取上下文 2.描述路徑 3.把路徑添加到上下文 4.渲染上下文
drawRect:畫線必須要在drawRect方法實現,因為只有在drawRect方法中才能獲取到根view相關聯上下文;當前控件即將顯示的時候調用,只調用一次;
注意:
drawRect不能手動調用;drawRect只能系統調用,每次系統調用drawRect方法之前,都會給drawRect方法傳遞一個跟當前view相關聯上下文;
執行[self.view setNeedsDisplay];
會調用drawRect。
效果圖
#define kRandomColor [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1.0] //隨機顏色
#define kLineCount 6 //干擾線的個數
#define kLineWidth 1.0 //干擾線的寬度
#define kCharCount 5 //需要驗證碼的個數
#define kFontSize [UIFont systemFontOfSize:arc4random() % 5 + 15] //字體大小
獲取隨機驗證碼
#pragma mark - 獲取隨機驗證碼
- (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"];
//隨機從素材數組中取出需要個數的字符串,拼接為驗證碼字符串存入驗證碼數組中
for (int i = 0; i < kCharCount; i ++){
NSInteger index = arc4random() % self.dataArray.count;
[self.authCodeStr insertString:[NSString stringWithFormat:@"%@",self.dataArray[index]] atIndex:i];
}
}
點擊view刷新驗證碼
//點擊界面切換驗證碼
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[self getAuthcode];
[self setNeedsDisplay];
}
繪制驗證碼和線條
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
self.backgroundColor = [UIColor whiteColor];
/*計算每個字符串顯示的位置*/
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條隨機色干擾線
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);
}
}