利用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);
}
}