用于ios本地动态生成验证码,效果如下:

demo.gif

  • 导入CoreGraphics.framework
    用于绘制图形

  • 封装UIView,便捷使用,代码如下:

AuthcodeView.h

#import <UIKit/UIKit.h>
@interface AuthcodeView : UIView
@property (strong, nonatomic) NSArray *dataArray;//字符素材数组
@property (strong, nonatomic) NSMutableString *authCodeStr;//验证码字符串@end

AuthcodeView.m

#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 6
#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 = [super initWithFrame:frame];    
   if (self)     {        
       self.layer.cornerRadius = 5.0f;        
       self.layer.masksToBounds = YES;        
       self.backgroundColor = kRandomColor;          
       [self getAuthcode];//获得随机验证码    
   }    
   return self;
}
#pragma mark 获得随机验证码
- (void)getAuthcode {    
   //字符串素材    
   _dataArray = [[NSArray alloc] 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 = [[NSMutableString alloc] initWithCapacity:kCharCount];    //随机从数组中选取需要个数的字符串,拼接为验证码字符串    
   for (int i = 0; i < kCharCount; i++)     {        
       NSInteger index = arc4random() % (_dataArray.count-1);        NSString *tempStr = [_dataArray objectAtIndex:index];        
       _authCodeStr = (NSMutableString *)[_authCodeStr stringByAppendingString:tempStr];    
   }
}
#pragma mark 点击界面切换验证码 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {    
   [self getAuthcode];    //setNeedsDisplay调用drawRect方法来实现view的绘制    
   [self setNeedsDisplay];
}  
- (void)drawRect:(CGRect)rect {    
   [super drawRect:rect];    //设置随机背景颜色    
   self.backgroundColor = kRandomColor;    //根据要显示的验证码字符串,根据长度,计算每个字符串显示的位置    
   NSString *text = [NSString stringWithFormat:@"%@",_authCodeStr];    CGSize cSize = [@"A" sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize: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 = [text characterAtIndex:i];        
       NSString *textC = [NSString stringWithFormat:@"%C", c];          
       [textC drawAtPoint:point withAttributes:@{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
  • 界面添加验证码

@interface AuthCodeViewController ()<UITextFieldDelegate, UIAlertViewDelegate>
{    
   AuthcodeView *authCodeView;    
   UITextField *_input;
}
@end
@implementation AuthCodeViewController
- (void)viewDidLoad {    
   [super viewDidLoad];    // Do any additional setup after loading the view.      
   self.view.backgroundColor = [UIColor whiteColor];    //显示验证码界面    
   authCodeView = [[AuthcodeView alloc] initWithFrame:CGRectMake(30, 100, self.view.frame.size.width-60, 40)];    
   [self.view addSubview:authCodeView];    //提示文字    
   UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 160, self.view.frame.size.width-100, 40)];    
   label.text = @"点击图片换验证码";    
   label.font = [UIFont systemFontOfSize:12];    
   label.textColor = [UIColor grayColor];    
   [self.view addSubview:label];    //添加输入框    
   _input = [[UITextField alloc] initWithFrame:CGRectMake(30, 220, self.view.frame.size.width-60, 40)];    
   _input.layer.borderColor = [UIColor lightGrayColor].CGColor;    
   _input.layer.borderWidth = 2.0;    
   _input.layer.cornerRadius = 5.0;    
   _input.font = [UIFont systemFontOfSize:21];    
   _input.placeholder = @"请输入验证码!";    
   _input.clearButtonMode = UITextFieldViewModeWhileEditing;    
   _input.backgroundColor = [UIColor clearColor];    
   _input.textAlignment = NSTextAlignmentCenter;    
   _input.returnKeyType = UIReturnKeyDone;    
   _input.delegate = self;    
   [self.view addSubview:_input];
}
#pragma mark 输入框代理,点击return 按钮 - (BOOL)textFieldShouldReturn:(UITextField *)textField {    
   //判断输入的是否为验证图片中显示的验证码    
   if ([_input.text isEqualToString:authCodeView.authCodeStr])     {        
       //正确弹出警告款提示正确        
       UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"恭喜您 ^o^" message:@"验证成功" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];        
       [alview show];    
   }    else     {        //验证不匹配,验证码和输入框抖动        
       CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.x"];        
       anim.repeatCount = 1;        
       anim.values = @[@-20,@20,@-20];//        [authCodeView.layer addAnimation:anim forKey:nil];        
       [_input.layer addAnimation:anim forKey:nil];    
   }    
   return YES;
}
#pragma mark 警告框中方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {    
   //清空输入框内容,收回键盘    
   if (buttonIndex==0)     {        
       _input.text = @"";        
       [_input resignFirstResponder];    
   }
}

iOS本地动态验证码生成-b的更多相关文章

  1. Web---图片验证码生成教程详解-从简单到复杂-从本地到前后台

    首先,我们先来看本地如何生成图片验证码的,再来写输出到网页的验证码如何实现. 先来看最简单的-实现的功能是,将一个字符串变成图片写入到文件中 实现代码: package cn.hncu.img; im ...

  2. C#之asp.net 及MVC 生成动态验证码:

    C#之asp.net 及MVC 生成动态验证码: 1.生成验证码字符串 // 随机生成指定长度的验证码字符串private string RandomCode(int length) { string ...

  3. Django之动态验证码的生成

    kind.html <!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...

  4. Servlet仿CSDN动态验证码的生成-带数字和字母

    林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 一.实现的思路: (1)首先,须要创建一个Servlet.该Servlet通过字节型响应给cl ...

  5. .NET中生成动态验证码

    .NET中生成动态验证码 验证码是图片上写上几个字,然后对这几个字做特殊处理,如扭曲.旋转.修改文字位置,然后加入一些线条,或加入一些特殊效果,使这些在人类能正常识别的同时,机器却很难识别出来,以达到 ...

  6. 由12306动态验证码想到的ASP.NET实现动态GIF验证码(附源码)

    背景: 12306网站推出“彩色动态验证码机制”,新版验证码不但经常出现字符叠压,还不停抖动,不少人大呼“看不清”,称“那个验证码,是毕加索的抽象画么!”铁总客服则表示:为了能正常购票只能这样.而多家 ...

  7. WWDC2014之iOS使用动态库 framework【转】

    from:http://www.cocoachina.com/industry/20140613/8810.html JUN 12TH, 2014 苹果的开放态度 WWDC2014上发布的Xcode6 ...

  8. WWDC2014之iOS使用动态库

    苹果的开放态度 WWDC2014上发布的Xcode6 beta版有了不少更新,其中令我惊讶的一个是苹果在iOS上开放了动态库,在Xcode6 Beta版的更新文档中是这样描述的: Frameworks ...

  9. Linux下使用Google Authenticator配置SSH登录动态验证码

    1.一般ssh登录服务器,只需要输入账号和密码.2.本教程的目的:在账号和密码之间再增加一个验证码,只有输入正确的验证码之后,再输入密码才能登录.这样就增强了ssh登录的安全性.3.账号.验证码.密码 ...

随机推荐

  1. 本机连接虚拟机Oracle时报错的解决办法

    虚拟机安装了Oracle服务器(桌面类)和客户端,里面使用plsql连接自己没有问题. 在本机连接虚拟机没有成功.虚拟机的地址是192.168.126.132,已经确认本机能ping通虚拟机. 先是报 ...

  2. Ajax具体使用

    Ajax在注册页面经常使用,当注册用户是用户名必须唯一时,要使用ajax获取表单中你输入的内容, 然后将这个数据利用XMLHttpRequest对象请求一个php文件,这个php文件接收到信息,查询数 ...

  3. Nginx - Rewrite Module

    Initially, the purpose of this module (as the name suggests) is to perform URL rewriting. This mecha ...

  4. Unity3D 判断鼠标是否按在UGUI上

    判断鼠标是否点击在UGUI上 #if UNITY_ANDROID && !UNITY_EDITOR #define ANDROID #endif #if UNITY_IPHONE &a ...

  5. WCF简介

    WCF(Windows communication Foundation),顾名思义,就是在windows平台下解决通信的基础框架.WCF做为.NET Framework 3.0的一个组件发布出来的, ...

  6. Java -- Thread中start和run方法的区别

    一.认识Thread的 start() 和 run() 1.start(): 我们先来看看API中对于该方法的介绍: 使该线程开始执行:Java 虚拟机调用该线程的 run 方法. 结果是两个线程并发 ...

  7. Android手机播放电脑视频文件-屌丝必备

    今天早上一到办公室,照常打开博客园看文章,看到有一片文章是用  http://www.cnblogs.com/wdfrog/p/3738180.html 看到这哥们实现的方法好复杂,又是配置电脑端,又 ...

  8. 牛客_Java_值传递(拷贝)不该表原来变量+传引用的话会一起改变

    总结: 许多编程语言都有2种方法将参数传递给方法------按值传递和按引用传递.  与其他语言不同,Java不允许程序员选择按值传递还是按引用传递各个参数,基本类型(byte--short--int ...

  9. css3学习笔记之渐变

    CSS3 线性渐变 语法 background: linear-gradient(direction, color-stop1, color-stop2, ...); 1 2 3 4 5 6 7 8 ...

  10. CSS样式一

    样式 首先明确: HTML标签也有标签的属性,CSS中的样式也称作为属性,而且某些html中的属性与css中的属性同名,并且作用也相同,但是属于不同的技术. 尺寸样式: 几乎所有的标签有可以设置 wi ...