混淆的验证码视图,是我们日常经常用到的功能模块之一,一般来说后台不会直接返回我们验证码的图片,一般需要我们将字符串信息转换成我们需要的视图;不管是转换成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);
}
网友评论