美文网首页iOS Developer
IOS验证码分析&实现

IOS验证码分析&实现

作者: dispath_once | 来源:发表于2017-06-14 22:15 被阅读132次

前言

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

分析&实现

  • 验证码产生,从数组从随机获取到指定个数的字符串,然后拼接成验证码,并绘制到view上面。
    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];
    }
  • 干扰线产生,在view的范围内随机获取两点,然后根据两点绘制线条
    //画干扰线
    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);
    }
  • 重写touchesBegan方法,使每点击一次生成新的验证码
//每次点击都重新生成验证码
  - (void)touchesBegan:(NSSet <UITouch *> *)touches withEvent:(UIEvent *)event {
    [self setNeedsDisplay];
}

小记

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

相关文章

网友评论

    本文标题:IOS验证码分析&实现

    本文链接:https://www.haomeiwen.com/subject/fdveqxtx.html