iOS gesture unlocking and fingerprint unlocking

Source: Internet
Author: User
effect

Find a way to use the picture online, Kkgesturelockview, but if you want to do animation aesthetics, you have to draw, on this basis to customize, first look at the effect


gesture Unlock

1. The first gesture to unlock the area is a custom button, when the user gestures received, according to the coordinates of the corresponding button into the array, further follow-up judgment
2. When the user's gesture is detected, the button is constantly redrawn to form an animation
3. The line that is then crossed by the gesture is also a view that is covered above the unlocked area, drawn on the left

1. Initialize

-(void) _lockviewinitialize{
    self.backgroundcolor = [Uicolor clearcolor];

    Self.linecolor = [[Uicolor blackcolor] colorwithalphacomponent:0.3];
    Self.linewidth = Klinedefaultwidth;

    Self.isshowinner = YES;
    Unlock area
    self.contentinsets = uiedgeinsetsmake (0, 0, 0, 0);
    Self.contentview = [[UIView alloc] Initwithframe:uiedgeinsetsinsetrect (Self.bounds, self.contentinsets)];    Self.contentView.backgroundColor = [Uicolor yellowcolor];
    [Self addSubview:self.contentView];
    Gesture Trajectory area
    Self.gesturelineview = [[Kkgesturelineview alloc] initWithFrame:self.bounds];
    Self.gestureLineView.backgroundColor = [Uicolor clearcolor];
    [Self addSubview:self.gestureLineView];

    Self.buttonsize = Cgsizemake (Knodedefaultwidth, knodedefaultheight);
    Invokes the number of setter methods to add
    Self.numberofgesturenodes = knumberofnodes to the button;
    Self.gesturenodesperrow = Knodesperrow;

}

2. Fixed coordinates

-(void) layoutsubviews{[Super Layoutsubviews];
    _gesturelineview.linecolor = [Uicolor Redcolor]; _gesturelineview.linewidth = self.isdotshow?

    0:klinedefaultwidth;
    Self.contentView.frame = Uiedgeinsetsinsetrect (Self.bounds, self.contentinsets); CGFloat Horizontalnodemargin = (self.contentview.bounds.size.width-self.buttonsize.width * self.gestureNodesPerRow)
    /(SELF.GESTURENODESPERROW-1);
    Nsuinteger numberofrows = CEILF ((self.numberofgesturenodes * 1.0/self.gesturenodesperrow)); CGFloat verticalnodemargin = (self.contentview.bounds.size.height-self.buttonsize.height *numberOfRows)/(

    NUMBEROFROWS-1);
        for (int i = 0; i < self.numberofgesturenodes i++) {int row = I/self.gesturenodesperrow;
        int column = i% Self.gesturenodesperrow;
        Kkgesturelockitemview *button = [Self.buttons objectatindex:i];
        Button.nodewith = _nodewidth?_nodewidth:18;

        Button.isshowinner = _isshowinner; Button.frame = CGRectmake (Floorf (self.buttonSize.width + horizontalnodemargin) * column), Floorf (Self.buttonSize.height +
    Verticalnodemargin) * row), self.buttonSize.width, self.buttonSize.height);
 }
}

3. Core Unlock area three methods
*touchesbegan
*touchesmoved
*touchesended

-(void) Touchesbegan: (Nsset *) touches withevent: (uievent *) event{//Get start coordinates uitouch *touch = [touches anyobject];
    Cgpoint Locationincontentview = [Touch LocationInView:self.contentView];
    Obtain the corresponding button according to the coordinates kkgesturelockitemview *touchedbutton = [self _buttoncontainsthepoint:locationincontentview]; If the start is not the button area does not draw if (Touchedbutton!= nil) {//Triggers to the button to animate [Touchedbutton Setitemviewtype:kkgestur
        Elockitemtypeselect]; [Touchedbutton startanimation];//Start animation//Add to selected array [_gesturelineview.selectedbuttons Addobject:touchedbutt

        On];

        _gesturelineview.trackedlocationincontentview = Locationincontentview; if (_delegateflags.didbeginwithpasscode) {[Self.delegate gesturelockview:self didbeginwithpasscode:[nsstring
        stringwithformat:@ "%d", (int) Touchedbutton.tag]]; }}-(void) touchesmoved: (Nsset *) touches withevent: (uievent *) event{//get to coordinates uitouch *touch = [Touches an
Yobject];    Cgpoint Locationincontentview = [Touch LocationInView:self.contentView]; 
        The gesture area is within the specified coordinates if (Cgrectcontainspoint (Self.contentView.bounds, Locationincontentview)) {//If triggered to the button area, the button is animated
        Kkgesturelockitemview *touchedbutton = [self _buttoncontainsthepoint:locationincontentview];
            if (Touchedbutton!= nil && [_gesturelineview.selectedbuttons indexofobject:touchedbutton]==nsnotfound) {
            [Touchedbutton Setitemviewtype:kkgesturelockitemtypeselect];
            [Touchedbutton startanimation];//begins animation [_gesturelineview.selectedbuttons Addobject:touchedbutton]; if ([_gesturelineview.selectedbuttons count] = = 1) {//if The touched button is the the Selected buttons,//it's beginning of the passcode creation if (_delegateflags.didbegi Nwithpasscode) {[Self.delegate gesturelockview:self didbeginwithpasscode:[nsstring stringWithFormat:@ "%d ", (int) Touchedbutton.tag]]; _gesturelineview.trackedlocationincontentview = Locationincontentview of the trace line is constantly drawn
        ;
    [_gesturelineview Setneedsdisplay]; }
}

4. The animation of gestures is nothing but a constant call to DrawRect
Here to introduce a few commonly used methods, concrete implementation is slowly try out, know the method is good, need to download their own demo see it

* 1. Cgcontextsetstrokecolorwithcolor the color of the Edge line  cgcontextsetfillcolorwithcolor Fill Color
 * 2. Width of Cgcontextsetlinewidth Edge line
 * 3. Cgcontextaddarc Draw a circle x,y for the dot coordinates, radius radius, startangle for the beginning of radians, endangle for the end of radians, clockwise 0 for the clockwise, 1 for counterclockwise.
 * 4. The Cgcontextdrawpath  draws the path, the first argument is the context, and the second parameter is the kcgpathfill--> fill kcgpathstroke--> the road strength  kcgpathfillstroke-- > Fill + Path
 * 5. Cgcontextstrokepath similar to the above border path drawing
 * 6. Cgcontextfillpath similar to the above fill drawing
 * 7. Cgcontextclearrect Cleanup Context
 * 8. The function of the cgcontextsavegstate and Cgcontextrestoregstate Cgcontextsavegstate is to push the current graphics state onto the stack. After that, changes you make to the state of the graph affect the subsequent drawing operations, but do not affect the copies stored on the stack. After the modification is complete, you can use the Cgcontextrestoregstate function to eject the state of the top of the stack and return to the previous graphic state. This push-and-eject approach is a quick way to go back to the previous graphics state, avoiding all state modifications individually, which is the only way to restore certain states, such as cropping paths, to their original settings
 * 9.  Cgcontextclip cropping Context
 * 10. Cgcontextaddellipseinrect Draw Ellipse
 * 11. Cgcontextaddquadcurvetopoint two points between positive cosine fluctuation, double point control
 * 12. Cgcontextdrawimage This will make the picture up and down.





Small knowledge, take this as an example to draw a gradient button with the drawing method

-(void) DrawRect: (cgrect) Rect {//Drawing code////general Declarations Cgcolorspaceref colorspace = Cgcolor
    Spacecreatedevicergb ();


    Cgcontextref context = Uigraphicsgetcurrentcontext ();
    Gradient Declarations cgfloat gradientlocations[] = {0, 0.32, 1}; Cggradientref gradient = cggradientcreatewithcolors (colorspace, __bridge cfarrayref) @[(ID) UIColor.greenColor.CGColor, (ID) [Mkjview mixcolor1:[uicolor Greencolor] color2:[uicolor Whitecolor] ratio:0.5].

    Cgcolor, (ID) UIColor.whiteColor.CGColor], gradientlocations);
    Oval Drawing uibezierpath* ovalpath = [Uibezierpath bezierpathwithovalinrect:cgrectmake (0, 0, 24, 24)];
    Cgcontextsavegstate (context);
    [Ovalpath Addclip];
    Cgcontextdrawlineargradient (context, gradient, Cgpointmake (0), Cgpointmake (12, 24), 0);


    Cgcontextrestoregstate (context);
    Text Drawing CGRect textrect = CGRectMake (6, 6, 13, 12);
        {nsstring* textcontent = @ "D"; Nsmutableparagraphstyle* TextStyle = NSMutableParagraphStyle.defaultParagraphStyle.mutableCopy;

        Textstyle.alignment = Nstextalignmentleft; nsdictionary* textfontattributes = @{nsfontattributename: [Uifont systemFontOfSize:UIFont.labelFontSize],

        NSForegroundColorAttributeName:UIColor.blackColor, Nsparagraphstyleattributename:textstyle}; CGFloat texttextheight = [Textcontent boundingrectwithsize:cgsizemake (TextRect.size.width, INFINITY) options:
        Nsstringdrawinguseslinefragmentorigin attributes:textfontattributes context:nil].size.height;
        Cgcontextsavegstate (context);
        Cgcontextcliptorect (context, textrect); [Textcontent Drawinrect:cgrectmake (Cgrectgetminx (Textrect), Cgrectgetminy (textrect) + (Cgrectgetheight (textRect)-
        Texttextheight)/2, Cgrectgetwidth (Textrect), texttextheight) withattributes:textfontattributes];
    Cgcontextrestoregstate (context);
    }////Cleanup cggradientrelease (gradient); Cgcolorspacerelease (colorspace); } + (Uicolor *) MixColor1: (uicolor*) Color1 Color2: (Uicolor *) Color2 ratio: (cgfloat) ratio {if (ratio > 1) Rat
    IO = 1; Const CGFLOAT * components1 = cgcolorgetcomponents (color1.
    Cgcolor); Const CGFLOAT * components2 = cgcolorgetcomponents (Color2.
    Cgcolor);
    NSLog (@ "Red1:%f", components1[0]);
    NSLog (@ "GREEN1:%f", components1[1]);
    NSLog (@ "Blue1:%f", components1[2]);
    NSLog (@ "RED2:%f", components2[0]);
    NSLog (@ "Green2:%f", components2[1]);

    NSLog (@ "Blue2:%f", components2[2]);
    NSLog (@ "ratio =%f", ratio);
    CGFloat r = components1[0]*ratio + components2[0]* (1-ratio);
    CGFloat g = components1[1]*ratio + components2[1]* (1-ratio);
    CGFloat B = components1[2]*ratio + components2[2]* (1-ratio);

    CGFloat alpha = components1[3]*ratio + components2[3]* (1-ratio);
return [Uicolor colorwithred:r green:g blue:b alpha:1]; }



5. Fingerprint unlock
1.canEvaluatePolicy to determine whether to support fingerprints or whether to open fingerprint
2.evaluatePolicy fingerprint verification, pop-up system box
3. Import the Localauthentication framework
4. Detail reference error details for fingerprint identification errors

-(BOOL) Istouchidenableornotbysystem {#ifdef __iphone_8_0 lacontext *mycontext = [[Lacontext alloc] init];

    Nserror *autherror = nil;
         if ([Mycontext canevaluatepolicy:lapolicydeviceownerauthenticationwithbiometrics Error:&autherror]) {/**
    Can verify fingerprint phone support and mobile phone open fingerprint mode * *;
    else {/** cannot verify the fingerprint handset does not support or the user does not open fingerprint mode */return no;
#else/** cannot verify the fingerprint/return no; #endif/* __iphone_8_0/}-(void) Startverifytouchid: (void (^) (void) Completeblock failure: (void (^) (void)) Failureblo

CK {NSString *touchidreason = [NSString stringwithformat:@ "I want to unlock%@", _appname];
    #ifdef __iphone_8_0 Lacontext *mycontext = [[Lacontext alloc] init];

    Nserror *autherror = nil;

    Hide "Enter Password" button mycontext.localizedfallbacktitle = @ ""; Show the authentication UI if ([Mycontext canevaluatepolicy:lapolicydeviceownerauthenticationwithbiometrics error: &autherror]) {[Mycontext evaluatepolicy:lapolicydeviceownerauthenticationwithbiometrics
                                Localizedreason:touchidreason reply:^ (BOOL success, Nserror *error) {

                                    if (success) {//User authenticated successfully, take appropriate action Dispatch_async (Dispatch_get_main_queue (), ^{/
                                        * * Fingerprint Verification success * *
                                    [Self verifysucceed:completeblock];

                                });  else {//User did not authenticate successfully, look at error and take appropriate
                                        Action Dispatch_async (Dispatch_get_main_queue (), ^{
           /**                              Fingerprint verification failure
                                    [Self authenticatedfailedwitherror:error failure:failureblock];

                                });
    }
                            }];

        else {//Could not evaluate policy, look at Autherror and present a appropriate message to user
        Dispatch_async (Dispatch_get_main_queue (), ^{[self evaluatepolicyfailedwitherror:nil];

    }); } #endif/* __iphone_8_0 */}

1. Note Here is a parameter, we are now using Lapolicydeviceownerauthenticationwithbiometrics, the default is TouchID after the failure will not jump to the password settings, If you change to lapolicydeviceownerauthentication, then the password will be set to the jump, or according to the requirements of the configuration
2. Another parameter Localizedreason is to configure the window to display fingerprint unlock prompts


Demo Address

Related Article

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.