生成图形验证码

来源:互联网 发布:mac air输入法怎么切换 编辑:程序博客网 时间:2024/05/16 23:33

在我们开发工程中,不免要用到图形验证码,当然可以使用简单的几个数字生成,但是这样太LOW,下面分享一个生成4位图形验证码的代码:

开发思路:生成随机几个字符,然后随机字符的字号,字体,颜色,


首先写一个数组,来存储我们图形验证码内容:(我的是文字字母)

NSArray *charArry = @[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"a",@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"a",@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",@"j",@"k",@"l",@"m",@"n",@"o",@"p",@"q",@"r",@"s",@"t",@"u",@"v",@"w",@"x",@"w",@"z",@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"G",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z"];

 codeStr= @"";//初始化---这个就是存储我们图形验证码的内容
    for (int i = 0; i<4; i ++) {
        int j = arc4random()%charArry.count;
        codeStr = [NSString stringWithFormat:@"%@%@",codeStr,charArry[j]];
    }//随机内容
    NSMutableArray  *fontArray = nil;
    fontArray = [[NSMutableArray alloc]init];
    for (NSString * familyName in [UIFont familyNames]) {
        for (NSString * fontName in [UIFont fontNamesForFamilyName:familyName]) {
            [fontArray addObject:fontName];
        }
    }//获取所有的字体
    NSMutableAttributedString *attributeString  = [[NSMutableAttributedString alloc]initWithString:codeStr];
    for (int i = 0; i < codeStr.length; i ++) {
        //这里的小技巧,每次只截取一个字符的范围
        UIFont *font = [UIFont fontWithName:fontArray[arc4random()%fontArray.count] size:arc4random()%13+13];//这个是随机一个字号
        UIColor *color = [UIColor hex:[NSString stringWithFormat:@"#%u%u%u%u%u%u",arc4random()%9,arc4random()%9,arc4random()%9,arc4random()%9,arc4random()%9,arc4random()%9]];//随机一个颜色,这个可以用自己方法生成
        [attributeString setAttributes:@{NSForegroundColorAttributeName:color,NSFontAttributeName:font} range:NSMakeRange(i, 1)];
    }
    self.codeLabel.attributedText = attributeString;//用一个Label 存储这个字


然后就是不区分大小写的比较,以确定输入字符是否正确

[codeStr compare:self.imgVerifTF.text options:NSCaseInsensitiveSearch]==NSOrderedSame;


可以在label上放置一个button button点击事件来触发切换图形验证码,在添加背景图片,效果更是6666的,至此一个漂亮的图形验证码完毕;

原创粉丝点击