iOS 生成本地验证码
在应用程序注册、登陆或者有关支付确认的界面,经常会用到验证码,验证码有的是通过手机发送获取的,有的是在本地点击获取的,通过手机发送获取的动态验证码可以使用第三方类库实现,本地点击获取的是在本地自己绘制的,下面我们来详细讲解一下本地生成动态验证码的过程。
导入CoreGraphics.framework
验证码封装了一个UIView,在使用的时候直接把这个View加到界面上使用
CaptchaView.h
#import <UIKit/UIKit.h> @interface CaptchaView : UIView @property (nonatomic, retain) NSArray *changeArray; //字符素材数组
@property (nonatomic, retain) NSMutableString *changeString; //验证码的字符串 @end
CaptchaView.m
#import "CaptchaView.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 CaptchaView
@synthesize changeString,changeArray; - (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) { self.layer.cornerRadius = 5.0; //设置layer圆角半径
self.layer.masksToBounds = YES; //隐藏边界
self.backgroundColor = kRandomColor; //显示一个随机验证码
[self changeCaptcha];
} return self;
}
#pragma mark 更换验证码,得到更换的验证码的字符串
-(void)changeCaptcha
{
//<一>从字符数组中随机抽取相应数量的字符,组成验证码字符串
//数组中存放的是全部可选的字符,可以是字母,也可以是中文
self.changeArray = [[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]; //如果能确定最大需要的容量,使用initWithCapacity:来设置,好处是当元素个数不超过容量时,添加元素不需要重新分配内存
NSMutableString *getStr = [[NSMutableString alloc] initWithCapacity:kCharCount];
self.changeString = [[NSMutableString alloc] initWithCapacity:kCharCount]; //随机从数组中选取需要个数的字符,然后拼接为一个字符串
for(int i = 0; i < kCharCount; i++)
{
NSInteger index = arc4random() % ([self.changeArray count] - 1);
getStr = [self.changeArray objectAtIndex:index]; self.changeString = (NSMutableString *)[self.changeString stringByAppendingString:getStr];
} //<2>从网络获取字符串,然后把得到的字符串在本地绘制出来(网络获取步骤在这省略)
// self.changeString = [NSMutableString stringWithString:@"杰瑞教育"];
} #pragma mark 点击view时调用,因为当前类自身就是UIView,点击更换验证码可以直接写到这个方法中,不用再额外添加手势
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//点击界面,切换验证码
[self changeCaptcha]; //setNeedsDisplay调用drawRect方法来实现view的绘制
[self setNeedsDisplay];
} #pragma mark 绘制界面(1.UIView初始化后自动调用; 2.调用setNeedsDisplay方法时会自动调用)
- (void)drawRect:(CGRect)rect {
// 重写父类方法,首先要调用父类的方法
[super drawRect:rect]; //设置随机背景颜色
self.backgroundColor = kRandomColor; //获得要显示验证码字符串,根据长度,计算每个字符显示的大概位置
NSString *text = [NSString stringWithFormat:@"%@",self.changeString];
CGSize cSize = [@"S" 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
<三>在界面上添加验证码
ViewController.m
#import "ViewController.h"
#import "CaptchaView.h" @interface ViewController ()<UITextFieldDelegate,UIAlertViewDelegate>
{
CaptchaView *_captchaView;
UITextField *_input;
} @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; //显示验证码界面
_captchaView = [[CaptchaView alloc] initWithFrame:CGRectMake(20, 40, 150, 40)];
[self.view addSubview:_captchaView]; //提示文字
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(190, 40, 100, 40)];
label.text = @"点击图片换验证码";
label.font = [UIFont systemFontOfSize:12];
label.textColor = [UIColor grayColor];
[self.view addSubview:label]; //添加输入框
_input = [[UITextField alloc] initWithFrame:CGRectMake(20, 100, 150, 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:_captchaView.changeString]) {
//正确弹出警告款提示正确
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];
[_captchaView.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];
}
}
@end
iOS 生成本地验证码的更多相关文章
- iOS生成本地随机验证码
原文链接:http://www.cnblogs.com/jerehedu/p/4527707.html 效果图:
- Python 生成随机验证码
Python生成随机验证码 Python生成随机验证码,需要使用PIL模块. 安装: 1 pip3 install pillow 基本使用 1. 创建图片 1 2 3 4 5 6 7 8 9 fro ...
- Python生成随机验证码
Python生成随机验证码,需要使用PIL模块. 安装: pip3 install pillow 基本使用 1.创建图片 from PIL import Image img = Image.new(m ...
- Android开发——本地验证码的简易实现
0. 前言 验证码无处不在.有人问我,你知道达芬奇password以下是什么吗,对.答案就是达芬奇验证码. 验证码一个最基本的作用就是防止恶意暴力破解登录,防止不间断的登录尝试,事实上能够在se ...
- HBuilderX生成本地打包App资源
http://ask.dcloud.net.cn/question/60254 概要 在HBuilderX中开发的应用可以提交到云端打包生成apk(Android平台)和ipa(iOS平台).如果本地 ...
- node使用xml-writer生成本地XML文件实例
npm中xml-writer文档的链接地址:https://www.npmjs.com/package/xml-writer npm中的文档比较简单,而且生成本地xml文件的demo并不正确.本篇是对 ...
- iOS 打开本地 其他应用程序(URL Types)
iOS 打开本地其他应用程序(URL Types) /*前言废话:Xcode是神奇的,是我所见到的编译器中最为神奇的,如:它可以同时运行两个甚至更多Project到我们模拟器上,可以同时使用一个模拟器 ...
- Java生成随机验证码
package com.tg.snail.core.util; import java.awt.Color; import java.awt.Font; import java.awt.Graphic ...
- PHP利用jquery生成各种验证码和Ajax验证
PHP生成验证码图片 PHP生成验证码的原理:使用PHP的GD库,生成一张带验证码的图片,并将验证码保存在Session中.PHP 生成验证码的大致流程有: .产生一张png的图片: .为图片设置背景 ...
随机推荐
- Can jxta be used to develop online card game (p2p style)?
Can jxta be used to develop online card game (p2p style)? https://www.java.net//node/677134 I am new ...
- Spring入门(10)-Spring JDBC
Spring入门(10)-Spring JDBC 0. 目录 JdbcTemplate介绍 JdbcTemplate常见方法 代码示例 参考资料 1. JdbcTemplate介绍 JdbcTempl ...
- jdk自带发布webservice服务
1.创建要发布的类 package com.test.webserive; import javax.jws.WebService; //targetNamespace定义命名空间 @WebServi ...
- (DP6.1.4.2)POJ 1088 滑雪
其实下面用到的是搜索.(呜呜,DP写的过了测试用例但是却总是AC不了,所以改用搜索来做了) /* * POJ_1088.cpp * * Created on: 2013年10月13日 * Author ...
- UVaLive 6859 Points (几何,凸包)
题意:给定 n 个点,让你用最长的周长把它们严格包围起来,边长只能用小格子边长或者是小格子对角线. 析:先把每个点的上下左右都放到一个集合中,然后求出一个凸包,然后先边长转成题目的方式,也好转两个点的 ...
- android中的Cursor类
转载: 使用过 SQLite 数据库的童鞋对 Cursor 应该不陌生,如果你是搞.net 开发你大可以把Cursor理解成 Ado.net 中的数据集合相当于dataReader.今天特地将它单独拿 ...
- Thinkphp框架 -- ajax无刷新上传图片
用Thinkphp框架做无刷新上传图片 视图层 View <!doctype html> <html lang="en"> <head> < ...
- cocos2d-x的初步学习二十一之iosandroid跨平台环境配置
这篇文章中,我们将来构建下跨平台开发的环境配置,我自己也是参考了别人了文章,折腾了几个小时,尤其是android的配置相对麻烦些.... 参考自子龙山人:http://www.cnblogs.com/ ...
- 密码强度应用(js)
<!-- 密码强度div --> <div id="tips" class="help-block"> <b class=&quo ...
- 支持向量机(SVM)非线性数据切割
支持向量机(SVM)非线性数据切割 1.目标 本指导中你将学到: l 当不可能线性切割训练数据时,如何定义SVM最优化问题. l 在这样的问题上.如何配置CvSVMParams中的參数满足你的SV ...