iOS development-Random image verification code

Source: Internet
Author: User

Sign-in in iOS projects often use random verification code, especially in the form of images generated by the code, you can reduce the use of third-party resources, only local generation and verification, this article describes the process of generating random picture verification code, including Arabic numerals 0-9, English capital letter A-Z, English lowercase letter A-Z, the generated captcha is case-sensitive. If you want to change to a case-insensitive, just need to add a judgment when the code is taken.

first, create a class that inherits from UIView and add the properties and methods required by the outside world in the. h file:
@property (Strong, nonatomic) nsmutablestring *authcodestr; // Verification Code String -(void) Getauthcode;

Second, add the macro definition in the. m file:
//Random background color#definekrandomcoloral [Uicolor colorwithred:arc4random ()% 256/256.0 green:arc4random ()% 256/256.0 blue:arc4random ()% 256 /256.0 alpha:0.5];//interference line Random color#defineKrandomcolor [Uicolor colorwithred:arc4random ()% 256/256.0 green:arc4random ()% 256/256.0 blue:arc4random ()% 256/ 256.0 Alpha:1];//number of interference lines#defineKlinecount 4//Interference line width#defineKlinewidth 1.0//number of verification codes#defineKcharcount 4//Verification Code size#defineKfontsize (Arc4random ()% 5 + 20)
Third, initialize:
- (Instancetype) initWithFrame: (cgrect) frame{    = [Super Initwithframe:frame];     if (self)    {        5.0f;         = YES;         = Krandomcolor;                [Self getauthcode]; // get a random verification code     }    return self ;}
Four, obtain the random verification code method:
#pragmaMark obtains a random verification code-(void) getauthcode{//string Footage_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]; //randomly select the required number of strings from the array, stitching it into a CAPTCHA string     for(inti =0; i < Kcharcount; i++) {Nsinteger index= Arc4random ()% (_dataarray.count-1); NSString*tempstr =[_dataarray Objectatindex:index]; _authcodestr= (Nsmutablestring *) [_authcodestr stringbyappendingstring:tempstr]; }}
Five, click the interface Switch Verification code:
#pragma Mark Click Interface Switch Verification code-(void) Touchesbegan: (Nsset *) touches withevent: (uievent *)event {    [self getauthcode];         // Setneedsdisplay Call the DrawRect method to implement view rendering     [self setneedsdisplay];}
Six, Draw:
#pragmaMark Draw-(void) DrawRect: (CGRect) rect{[Super Drawrect:rect]; //set a random background colorSelf.backgroundcolor =krandomcoloral; //calculates the position of each string displayed according to the length of the CAPTCHA string to displayNSString *text = [NSString stringWithFormat:@"%@", _authcodestr]; Cgsize cSize= [@"A"Sizewithattributes:@{nsfontattributename:[uifont systemfontofsize: -]}]; intwidth = rect.size.width/text.length-Csize.width; intHeight = rect.size.height-Csize.height;        Cgpoint Point; //draw each character in turn to set the font size, color, style, and so on for each character displayed    floatpx,py;  for(inti =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: @{uifontdescr Iptorfamilyattribute:@"Marion", Uifontdescriptornameattribute:@"HANZIPENSC-W3", Uifontdescriptorsizeattribute: @40.0, Uifontdescriptormatrixattribute:[nsvalue Valuewithcgaffinetran Sform:cgaffinetransformmakerotation (M_1_pi* (Arc4random ()%2 ))                                                                                        ]}]; Uifont* Font =[Uifont fontwithdescriptor:attributefontdescriptor size:kfontsize]; Uicolor*color =Krandomcolor;            [TEXTC Drawatpoint:point Withattributes:@{nsfontattributename:font,nsforegroundcolorattributename:color}]; }            //call DrawRect: Before the system pushes a cgcontextref into the stack, the call Uigraphicsgetcurrentcontext () takes the top of the stack cgcontextrefCgcontextref context =Uigraphicsgetcurrentcontext (); //Set line widthcgcontextsetlinewidth (context, klinewidth); //Draw Interference Lines     for(inti =0; i < Klinecount; i++) {Uicolor*color =Krandomcolor; Cgcontextsetstrokecolorwithcolor (context, color. Cgcolor);//Set line Fill Color//set the starting point of a linePX = Arc4random ()% (int) Rect.size.width; PY= Arc4random ()% (int) Rect.size.height;        Cgcontextmovetopoint (context, PX, PY); //set line end pointPX = Arc4random ()% (int) Rect.size.width; PY= Arc4random ()% (int) Rect.size.height;        Cgcontextaddlinetopoint (context, PX, PY); //Draw LineCgcontextstrokepath (context); }}
call, called in the class that needs to use the CAPTCHA:1. Define attributes:
@property (nonatomic, Strong) Maxauthcodeview * authcodeimage; /* *< Verification Code View */
2. Initialize:
Self.authcodeimage = [[Maxauthcodeview alloc] Initwithframe:cgrectmake (60 )];    [Self.view AddSubview:self.authcodeImage];    [Self.authcodeimage Getauthcode];
3. Get Verification Code:
NSLog (@ "%@", SELF.AUTHCODEIMAGE.AUTHCODESTR);
Eight, I hope you can get useful information, thank you!

Demo:https://github.com/maxli7681/authcode

iOS development-Random image verification code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.