iOS动态验证码实现

来源:互联网 发布:mac怎样安装pc360游戏 编辑:程序博客网 时间:2024/05/19 04:29

//

//  AuthcodeView.h

//  BSbracelet

//

//  Created by Christopher on 17/5/16.

//  Copyright © 2017 ZTracy. All rights reserved.

//


#import <UIKit/UIKit.h>


@interface AuthcodeView : UIView

@property (strong,nonatomic) NSArray *dataArray;//字符素材数组


@property (strong,nonatomic) NSMutableString *authCodeStr;//验证码字符串

@end




//

//  AuthcodeView.m

//  BSbracelet

//

//  Created by Christopher on 17/5/16.

//  Copyright © 2017 ZTracy. All rights reserved.

//


#import "AuthcodeView.h"


#define kRandomColor  [UIColor colorWithRed:arc4random() % 256 / 256.0 green:arc4random() %256 / 256.0 blue:arc4random() %256 / 256.0 alpha:1.0];

#define kLineCount 6

#define kLineWidth 1.0

#define kCharCount 4

#define kFontSize [UIFont systemFontOfSize:arc4random() % 5 +15]


@implementation AuthcodeView


/*

// Only override drawRect: if you perform custom drawing.

// An empty implementation adversely affects performance during animation.

- (void)drawRect:(CGRect)rect {

    // Drawing code

}

*/

- (instancetype)initWithFrame:(CGRect)frame

{

    self = [superinitWithFrame:frame];

    if (self)

    {

        self.layer.cornerRadius =5.0f;

        self.layer.masksToBounds =YES;

        self.backgroundColor =kRandomColor;

        

        [selfgetAuthcode];//获得随机验证码

    }

    returnself;

}


#pragma mark 获得随机验证码

- (void)getAuthcode

{

    //字符串素材

    _dataArray = [[NSArrayalloc] initWithObjects:@"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",@"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",nil];

    

    _authCodeStr = [[NSMutableStringalloc] initWithCapacity:kCharCount];

    //随机从数组中选取需要个数的字符串,拼接为验证码字符串

    for (int i =0; i < kCharCount; i++)

    {

        NSInteger index =arc4random() % (_dataArray.count-1);

        NSString *tempStr = [_dataArrayobjectAtIndex:index];

        _authCodeStr = (NSMutableString *)[_authCodeStrstringByAppendingString:tempStr];

    }

}


#pragma mark 点击界面切换验证码

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    [selfgetAuthcode];

    

    //setNeedsDisplay调用drawRect方法来实现view的绘制

    [selfsetNeedsDisplay];

}


- (void)drawRect:(CGRect)rect

{

    [superdrawRect:rect];

    

    //设置随机背景颜色

    self.backgroundColor =kRandomColor;

    

    //根据要显示的验证码字符串,根据长度,计算每个字符串显示的位置

    NSString *text = [NSStringstringWithFormat:@"%@",_authCodeStr];

    

    CGSize cSize = [@"A"sizeWithAttributes:@{NSFontAttributeName:[UIFontsystemFontOfSize:20]}];

    

    int width = rect.size.width/text.length - cSize.width;

    int height = rect.size.height - cSize.height;

    

    CGPoint point;

    

    //依次绘制每一个字符,可以设置显示的每个字符的字体大小、颜色、样式等

    float pX,pY;

    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 = [textcharacterAtIndex:i];

        NSString *textC = [NSStringstringWithFormat:@"%C", c];

        

        [textC drawAtPoint:pointwithAttributes:@{NSFontAttributeName:kFontSize}];

    }

    

    //调用drawRect:之前,系统会向栈中压入一个CGContextRef,调用UIGraphicsGetCurrentContext()会取栈顶的CGContextRef

    CGContextRef context =UIGraphicsGetCurrentContext();

    //设置线条宽度

    CGContextSetLineWidth(context,kLineWidth);

    

    //绘制干扰线

    for (int i =0; i < kLineCount; i++)

    {

        UIColor *color =kRandomColor;

        CGContextSetStrokeColorWithColor(context, color.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);

    }

}

@end


使用

-(void)recordBtnClick:(UIButton *)recordBtn

{

    DomodelView = [[UIViewalloc]initWithFrame:CGRectMake(0,0,kScreenWidth,kScreenHeight)];

    DomodelView.backgroundColor = [UIColorcolorWithRed:0.3green:0.3blue:0.3alpha:0.6];

    authBgview = [[UIViewalloc]initWithFrame:CGRectMake(30,120, self.view.frame.size.width-60,220)];

    authBgview.backgroundColor = [UIColorwhiteColor]; //显示验证码界面

    authBgview.layer.cornerRadius =8;

    authBgview.layer.masksToBounds =YES;

    

    authCodeView = [[AuthcodeViewalloc] initWithFrame:CGRectMake(10,10, kScreenWidth-80,45)];

    [authBgviewaddSubview:authCodeView];

    

        //提示文字

    UILabel *label = [[UILabelalloc] initWithFrame:CGRectMake(10,65, kScreenWidth-80,40)];

    label.text =@"点击图片换验证码";

    label.font = [UIFontsystemFontOfSize:15];

    label.textColor = [UIColorgrayColor];

    [authBgviewaddSubview:label];

    

    //添加输入框

    _input = [[UITextFieldalloc] initWithFrame:CGRectMake(10,120, kScreenWidth-80,40)];

    _input.layer.borderColor = [UIColorlightGrayColor].CGColor;

    _input.layer.borderWidth =2.0;

    _input.layer.cornerRadius =5.0;

    _input.font = [UIFontsystemFontOfSize:21];

    _input.placeholder =@"请输入验证码!";

    _input.clearButtonMode =UITextFieldViewModeWhileEditing;

    _input.backgroundColor = [UIColorclearColor];

    _input.textAlignment =NSTextAlignmentCenter;

    _input.returnKeyType =UIReturnKeyDone;

    _input.delegate =self;

    [authBgviewaddSubview:_input];


    UIButton *closeBtn = [[UIButtonalloc] initWithFrame:CGRectMake(10,170, kScreenWidth-80,40)];

    [closeBtn addTarget:selfaction:@selector(removeview)forControlEvents:UIControlEventTouchUpInside];

    closeBtn.backgroundColor =RGBCOLOR(34,151,216);

    [closeBtn setTitle:@"关闭"forState: UIControlStateNormal];

    [authBgviewaddSubview:closeBtn];

    

    [DomodelViewaddSubview:authBgview];

     [self.viewaddSubview:DomodelView];

//    InvoiceRecordViewController *InvoiceRecordVc = [[InvoiceRecordViewController alloc] initWithNibName:@"InvoiceRecordViewController" bundle:nil];

//    [self.navigationController pushViewController:InvoiceRecordVc animated:YES];

}


#pragma mark 输入框代理,点击return按钮

- (BOOL)textFieldShouldReturn:(UITextField *)textField

{

    //判断输入的是否为验证图片中显示的验证码

    if([_input.textcompare:authCodeView.authCodeStroptions:NSCaseInsensitiveSearch |NSNumericSearch] ==NSOrderedSame)

    {

        //正确弹出警告款提示正确

        //        UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"恭喜您 ^o^" message:@"验证成功" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];

        //        [alview show];

        [DomodelViewremoveFromSuperview];

        InvoiceRecordViewController *InvoiceRecordVc = [[InvoiceRecordViewControlleralloc] initWithNibName:@"InvoiceRecordViewController"bundle:nil];

        [self.navigationControllerpushViewController:InvoiceRecordVcanimated:YES];

    }

    else

    {

        //验证不匹配,验证码和输入框抖动

        CAKeyframeAnimation *anim = [CAKeyframeAnimationanimationWithKeyPath:@"transform.translation.x"];

        anim.repeatCount =1;

        anim.values =@[@-20,@20,@-20];

        //        [authCodeView.layer addAnimation:anim forKey:nil];

        [_input.layeraddAnimation:anim forKey:nil];

    }

    

    returnYES;

}




原创粉丝点击