In the application registration, login or about the payment confirmation interface, often use the verification code, the verification code is sent through the mobile phone to obtain, some in the local click to obtain, through the mobile phone to obtain the dynamic verification code can use the third-party class library implementation, local Click to obtain the local self-drawn, Let's take a look at the process of generating dynamic verification code locally.
< a > Import coregraphics.framework
< two > verification code encapsulates a uiview that is used to add the view directly to the interface.
CaptchaView.h
#import <UIKit/UIKit.h> @interface Captchaview:uiview@property (nonatomic, retain) Nsarray *changearray; Character footage array @property (nonatomic, retain) nsmutablestring *changestring; The string @end of the verification code
captchaview.m
#import "CaptchaView.h" #define Krandomcolor [Uicolor colorwithred:arc4random ()% 256/256.0 green:arc4random ()% 256/2 56.0 blue:arc4random ()% 256/256.0 alpha:1.0]; #define Klinecount 6#define klinewidth 1.0#define kcharcount 6#define kFon tsize [Uifont systemfontofsize:arc4random ()% 5 +] @implementation captchaview@synthesize changestring,changearray;- (instancetype) initWithFrame: (CGRect) frame{if (self = [Super Initwithframe:frame]) {Self.layer.cornerRa Dius = 5.0; Set the layer fillet radius self.layer.masksToBounds = YES; Hide boundary self.backgroundcolor = Krandomcolor; Displays a random verification code [self Changecaptcha]; } return self;} #pragma mark replace the verification code, get the replacement captcha string-(void) changecaptcha{//< > randomly extracts the corresponding number of characters from the character array, constituting the CAPTCHA string//array that holds all the optional characters, which can be letters, can also be Chinese 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", @ "Jay", @ "Rui", @ "teach", @ "Yu", Nil]; If you can determine the maximum required capacity, use initwithcapacity: To set up, the advantage is that when the number of elements does not exceed the capacity, the added element does not need to reallocate memory nsmutablestring *getstr = [nsmutablestring Alloc] Initwithcapacity:kcharcount]; self.changestring = [[Nsmutablestring alloc] initwithcapacity:kcharcount]; Randomly select the required number of characters from the array, and then stitch into a string 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> gets the string from the network and draws the resulting string locally (the network gets the step in this omission)//self.changestring = [nsmutablestring stringwithstring:@ "Jerry Education"] ;} #pragma mark clicks on the view, because the current class itself is UIView, click the replacement verification code can be directly written into this method, no additional gestures-(void) Touchesbegan: (Nsset *) touches withevent :(uievent *)event{//Click on the interface to toggle the captcha [self changecaptcha]; Setneedsdisplay calls the DrawRect method to implement the view's drawing [self setneedsdisplay];} #pragma mark Draw interface (1. UIView is automatically called after initialization; 2. Called automatically when the Setneedsdisplay method is invoked)-(void) DrawRect: (cgrect) Rect {//Overrides the parent class method, first calling the method of the parent class [Super Drawrect:rec T]; Set random background color self.backgroundcolor = Krandomcolor; Get the approximate location to display the CAPTCHA string, depending on the length, of each character display 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; Draw each character in turn, you can set the font size, color, style and so on for each character displayed 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}]; }//Call DrawRect: Before the system pushes a cgcontextref into the stack, the call Uigraphicsgetcurrentcontext () takes the top cgcontextref cgcontextref context = Uigraphicsgetcurrentcontext (); Set the Draw line width cgcontextsetlinewidth (context, klinewidth); Draw the color line for the disturbance for (int i = 0; i < Klinecount; i++) {//Set the random color of the line uicolor *color = Krandomcolor; Cgcontextsetstrokecolorwithcolor (context, [color Cgcolor]); Sets the starting point of the line PX = Arc4random ()% (int) rect.size.width; PY = Arc4random ()% (int) rect.size.height; Cgcontextmovetopoint (context, PX, PY); Set Line End pX = arc4random ()% (int) rect.size.width; PY = Arc4random ()% (int) rect.size.height; Cgcontextaddlinetopoint (context, PX, PY); Draw line Cgcontextstrokepath (context); }} @end
< three > Add verification code on the interface
viewcontroller.m
#import "ViewController.h" #import "CaptchaView.h" @interface Viewcontroller () <uitextfielddelegate, uialertviewdelegate>{Captchaview *_captchaview; Uitextfield *_input;} @end @implementation viewcontroller-(void) viewdidload {[Super viewdidload]; Display verification Code Interface _captchaview = [[Captchaview alloc] Initwithframe:cgrectmake (20, 40, 150, 40)]; [Self.view Addsubview:_captchaview]; Hint text UILabel *label = [[UILabel alloc] Initwithframe:cgrectmake (190, 40, 100, 40)]; Label.text = @ "Click on the image for verification Code"; Label.font = [Uifont systemfontofsize:12]; Label.textcolor = [Uicolor Graycolor]; [Self.view Addsubview:label]; Add input box _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 = @ "Please enter the verification code!"; _input.clearbuttonmode = Uitextfieldviewmodewhileediting; _input.backgroundcolor = [Uicolor Clearcolor]; _input.textalignment = Nstextalignmentcenter; _input.returnkeytype = Uireturnkeydone; _input.delegate = self; [Self.view addsubview:_input];} #pragma the Mark Input Box protocol method, click the Return button-(BOOL) Textfieldshouldreturn: (Uitextfield *) textfield{//Determine if the input is a verification code for verifying the image display if ([_i Nput.text isequaltostring:_captchaview.changestring]) {//correct pop-up warning prompt is correct uialertview *alview = [[Uialertview al LOC] initwithtitle:@ "Congratulations on your ^o^" message:@ "Verification Success" Delegate:self cancelbuttontitle:@ "OK" otherbuttontitles:nil, nil]; [Alview show]; } else {//validation mismatch, Verification code and input box shaking cakeyframeanimation *anim = [cakeyframeanimation animationwithkeypath:@ "tra Nsform.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 The Mark Warning box method-(void) Alertview: (Uialertview *)Alertview Clickedbuttonatindex: (nsinteger) buttonindex{//Empty input box contents, retract keyboard if (buttonindex==0) {_input.text = @ "" ; [_input Resignfirstresponder]; }} @end
To learn more about the small partners, you can click to view the source code , run the test yourself.
Jerry Education
Source:http://blog.csdn.net/jerehedu
This article is the copyright of Yantai Jerry Education Technology Co., Ltd. and CSDN Common, welcome reprint, but without the author's consent must retain this paragraph statement, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility.
IOS generates local verification code