#import <UIKit/UIKit.h>
@interface AuthcodeView : UIView
@property (strong, nonatomic) NSArray *dataArray;
@property (strong, nonatomic) NSMutableString *authCodeStr;
@end
#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
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.layer.cornerRadius = 5.0f;
self.layer.masksToBounds = YES;
self.backgroundColor = [UIColor whiteColor];
[self getAuthcode];
}
return self;
}
#pragma mark 获得随机验证码
- (void)getAuthcode {
self.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];
self.authCodeStr = [[NSMutableString alloc] initWithCapacity:kCharCount];
for (int i = 0; i < kCharCount; i++) {
NSInteger index = arc4random() % (self.dataArray.count-1);
NSString *tempStr = [self.dataArray objectAtIndex:index];
self.authCodeStr = (NSMutableString *)[self.authCodeStr stringByAppendingString:tempStr];
}
}
#pragma mark 点击界面切换验证码
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self getAuthcode];
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
self.backgroundColor = [UIColor whiteColor];
NSString *text = [NSString stringWithFormat:@"%@",self.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}];
}
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