iOS Developer

IOS验证码分析&实现

2017-06-14  本文已影响132人  dispath_once

前言

公司项目中在获取短信验证码的时候需要手动的输入图文验证码,防止多次获取验证码以及恶意刷验证码;通过分析和实践最终实现了项目要求的效果,这个verificationCodeDemo里面包含了demo和对应的view。如果大家喜欢记得Star哦😁😁😁

分析&实现

    NSArray *charArray = @[@"a", @"b", @"c", @"d", @"e", @"f", @"g", @"h", @"i", @"j", @"k", @"l", @"m", @"n", @"o", @"p", @"q", @"r", @"s", @"t", @"u", @"v", @"w", @"x", @"y", @"z", @"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z"];
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    //画背景颜色
    CGContextSetFillColorWithColor(context, randCGColor());
    CGContextFillRect(context, rect);

    NSMutableString *string = [NSMutableString string];
    //画随机字符串
    for (int i = 0; i < self.codeCount; i++) {
        NSString *c = charArray[arc4random_uniform((int)charArray.count)];
        [c drawAtPoint:CGPointMake(self.bounds.size.width / (self.codeCount * 1.f) * i + self.bounds.size.width / (self.codeCount * 2.f) - self.fontSize / 2, self.bounds.size.height / 2.f - self.fontSize / 2) withAttributes:@{ NSFontAttributeName:[UIFont systemFontOfSize:self.fontSize], NSForegroundColorAttributeName:randUIColor() }];
        [string appendString:c];
    }
    //画干扰线
    for (int i = 0; i < self.disturbLineCount; i++) {
        CGContextSetLineWidth(context, 1);
        CGContextSetStrokeColorWithColor(context, randCGColor());
        CGContextMoveToPoint(context, arc4random_uniform(self.bounds.size.width), arc4random_uniform(self.bounds.size.height));
        CGContextAddLineToPoint(context, arc4random_uniform(self.bounds.size.width), arc4random_uniform(self.bounds.size.height));
        CGContextStrokePath(context);
    }
//每次点击都重新生成验证码
  - (void)touchesBegan:(NSSet <UITouch *> *)touches withEvent:(UIEvent *)event {
    [self setNeedsDisplay];
}

小记

通过这个小demo的编写,让自己再次熟悉了CoreGraphics框架里面的一些常用的方法的使用和注意事项。

上一篇 下一篇

猜你喜欢

热点阅读