相关引用
基本原理
1. 将要显示的字符、数字、特殊字符等存入到一个数组中。
2. 随机从数组中获取规定个数的字符并将其丢入到属性字符串中。
3. 一定范围你设置属性字符串中的每个字的x与y。
4. 设置属性字符串的字体大小、左右倾斜度,形成验证码。
![](https://anchoritefiligod.gitee.io/blogs/styles/images/resources/0C37EEA00646D859F321805B2B885074.png)
相关代码
#import <UIKit/UIKit.h>
@interface AuthcodeView : UIView
@property (strong, nonatomic) NSArray *dataArray;
@property (strong, nonatomic) NSMutableString *authCodeStr;
@end
#import "AuthcodeView.h"
#define kCharCount 4 // 验证码显示的字数
#define kFontSize [UIFont systemFontOfSize:18] // 字号
@implementation AuthcodeView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
self.layer.borderWidth = 1;
self.layer.borderColor = [[UIColor darkGrayColor] CGColor];
self.layer.cornerRadius = 2.0f;
self.layer.masksToBounds = YES;
self.backgroundColor = [UIColor clearColor];
[self getAuthcode];
}
return self;
}
#pragma mark 获得随机验证码
- (void)getAuthcode
{
_dataArray = [[NSArray alloc] initWithObjects:@"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];
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
NSString *text = [NSString stringWithFormat:@"%@",_authCodeStr];
CGSize cSize = [@"A" sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:18]}];
int height = rect.size.height - cSize.height;
CGPoint point;
float pX,pY;
for ( int i = 0; i<text.length; i++)
{
pX = (rect.size.width-3)/text.length * i+3;
pY = arc4random() % (height-5) + 2.5;
point = CGPointMake(pX, pY);
unichar c = [text characterAtIndex:i];
NSString *textC = [NSString stringWithFormat:@"%C", c];
[textC drawAtPoint:point withAttributes:@{NSFontAttributeName:kFontSize,NSObliquenessAttributeName:@(0.5-(arc4random()%100)/100.0)}];
}
}
@end