1. 程式人生 > >iOS開發-隨機圖片驗證碼

iOS開發-隨機圖片驗證碼

ble 字母 ins cnblogs point cgpoint back 第三方 text

在iOS項目中登錄註冊經常會用到隨機驗證碼,尤其是以圖片形式生成的驗證碼,可以減少使用第三方資源的代碼使用,只在本地生成並驗證即可,本文即介紹生成隨機圖片驗證碼的流程,驗證碼包括阿拉伯數字0-9,英文大寫字母A-Z,英文小寫字母a-z,生成的驗證碼區分大小寫。若想改成不區分大小寫,只需要在取碼的時候添加判斷即可。

一、首先創建一個繼承自UIView的類,在.h文件中添加外界需要的屬性和方法:

@property (strong, nonatomic) NSMutableString *authCodeStr;//驗證碼字符串
- (void)getAuthcode;

二、在.m文件中添加宏定義:

//背景隨機顏色
#define kRandomColorAL  [UIColor colorWithRed:arc4random() % 256 / 256.0 green:arc4random() % 256 / 256.0 blue:arc4random() % 256 / 256.0 alpha:0.5];
//幹擾線隨機顏色
#define kRandomColor  [UIColor colorWithRed:arc4random() % 256 / 256.0 green:arc4random() % 256 / 256.0 blue:arc4random() % 256 / 256.0 alpha:1];
//
幹擾線數量 #define kLineCount 4 //幹擾線寬度 #define kLineWidth 1.0 //驗證碼數量 #define kCharCount 4 //驗證碼大小 #define kFontSize (arc4random() % 5 + 20)

三、初始化:

- (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];
}

六、繪制:

#pragma mark 繪制
- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    
    //設置隨機背景顏色
    self.backgroundColor = kRandomColorAL;
    
    //根據要顯示的驗證碼字符串,根據長度,計算每個字符串顯示的位置
    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];
        UIFontDescriptor *attributeFontDescriptor = [UIFontDescriptor fontDescriptorWithFontAttributes:
                                                     @{UIFontDescriptorFamilyAttribute: @"Marion",
                                                       UIFontDescriptorNameAttribute:@"HanziPenSC-W3",
                                                       UIFontDescriptorSizeAttribute: @40.0,
                                                       UIFontDescriptorMatrixAttribute:[NSValue valueWithCGAffineTransform:CGAffineTransformMakeRotation(M_1_PI*(arc4random() % 2 ))
                                                                                        ]}];
        UIFont * font = [UIFont fontWithDescriptor:attributeFontDescriptor size:kFontSize];
        UIColor *color = kRandomColor;
        [textC drawAtPoint:point withAttributes:@{NSFontAttributeName:font,NSForegroundColorAttributeName:color}];
        
    }
    
    
    //調用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);
    }
}

七、調用,在需要使用驗證碼的類中調用:

1、定義屬性:

@property (nonatomic, strong) MaxAuthCodeView * authcodeImage;/**< 驗證碼視圖*/

2、初始化:

self.authcodeImage = [[MaxAuthCodeView alloc] initWithFrame:CGRectMake(50, 100, 120, 60)];
    [self.view addSubview:self.authcodeImage];
    [self.authcodeImage getAuthcode];

3、獲取驗證碼:

NSLog(@"%@",self.authcodeImage.authCodeStr);

八、希望各位能夠獲取到有用的信息,謝謝!

demo下載地址:https://github.com/MaxLi7681/AuthCode

iOS開發-隨機圖片驗證碼