IOS coreanimation Basic Animation cabasicanimation

Source: Internet
Author: User

This article refers to: http://www.cnblogs.com/kenshincui/p/3972100.html#autoid-3-0-0 summary:

Core Animation

 *
Implementation of IOS Core animations

Coreanimation (included in the quartz core frame), in iOS core animations are divided into several categories (base animation, keyframe animation, animation Group, transition animation,)


Caanimation: Core animation of the basic class, can not be used directly, responsible for the animation running time speed control, to achieve the Camediatiming protocol


Capropertyanimation: The base class for property animations (animated by properties, note is animated), cannot be used directly


Caanimationgroup: Animation group, animation group is a combination of pattern design, you can use animation group to do all the animation behavior of the unified control, all animation effects in the group can be executed concurrently (executed together)


Catransition: Transition animation, primarily animated with filters


Cabasicanimation: Base animation, animated parameter control via property modification, only initial state and end state


cakeyframeanimation: Keyframe animation, also is the Pass property for animation adoption number control, but unlike the basic animation is that he can control multiple states

Basic animation, Keyframe animation, are property animation, that is, by modifying the property values to animate, developers only need to set the initial and end values, intermediate process animation (motion tween) by the system automatic calculation, and the basic animation is different from the key frame animation can set multiple property values, The tween animation in the middle of every two attributes is completed by the system, so the underlying animation from this angle is another keyframe animation of the Keyframe


Directly on the code, the comments are full, easy to understand:



<span style= "FONT-SIZE:24PX;" >////viewcontroller.m//coreanimation////Created by the Emperor Phlogistic Demon on 16/5/25.//copyright©2016 year. All rights reserved.//#import "ViewController.h" #define WIDTH 50//Width @interface viewcontroller () @property (nonatomic, S    Trong) Calayer *basicanilayer, @end @implementation viewcontroller-(void) viewdidload {[Super viewdidload];        Do any additional setup after loading the view.        Self.view.backgroundColor = [Uicolor Whitecolor];        Animation of small spheres//[self drawmylayer];        Drawing with proxy method//[self drawrollimageview];    Basic animation [self basiceanimation];    }/** * Core Animation * iOS Core Animation implementation Coreanimation (included in the quartz core frame), in iOS core animations are divided into several categories (base animation, keyframe animation, animation Group, transition animation,) Caanimation: Core animation of the basic class, can not be used directly, is responsible for the animation running time speed control, the realization of the Camediatiming protocol Capropertyanimation: Property animation of the base class (through the property animation settings, note is animated properties ), cannot be used directly Caanimationgroup: Animation Group, animation group is a combination of pattern design, can be animated group to all the animation behavior of the unified control, all the animation effects in the group can be executed concurrently (executed together) Catransition: Transition animation, mainly through Filters for animating effects settings CabasIcanimation: Basic animation, animation parameter control through property modification, only the initial state and end state cakeyframeanimation: Keyframe animation, also is the Pass property for animation adoption number control, but unlike the basic animation is that he can multiple state control base Animation, keyframe animation, are property animation, is to modify the property value to produce animation effect, the developer only need to set the initial value and the end value, the intermediate process animation (motion tween) by the system automatic calculation, and the basic animation is different from the key frame animation can set multiple property values, The tweened animation in the middle of each of the two attributes is done by the system, so the underlying animation from this angle is another keyframe animation */#pragma mark---basic animation/** * Animation creation steps * 1. Initializes the animation and sets the animation property 2. Set the animation property initial value (which can be omitted), end value, and other animation properties 3.    Animate the Layer */-(void) basiceanimation{//Set the background (note that the picture is in the root view) UIImage *backimage = [UIImage imagenamed:@ "HAHA1"];        Self.view.backgroundColor = [Uicolor colorwithpatternimage:backimage];    Customizing a layer _basicanilayer = [[Calayer alloc] init];    _basicanilayer.bounds = CGRectMake (0, 0, 50, 50);    _basicanilayer.position = Cgpointmake (50, 150); _basicanilayer.contents = (ID) [UIImage imagenamed:@ "Hudie"].    Cgimage;        [Self.view.layer Addsublayer:_basicanilayer];    } #pragma mark----motion Animation-(void) Translationanimation: (cgpoint) location{//1. Create animations and animate properties (animate a property of Calayer by KeyPath) Cabasicanimation *basIcanimation = [cabasicanimation animationwithkeypath:@ "position"]; 2. Set other animation property initial and end values Basicanimation.fromvalue = [Nsvalue valuewithcgpoint:_basicanilayer.position];      Can not be set, default is layer initial value state basicanimation.tovalue = [Nsvalue valuewithcgpoint:location];        NSLog (@ "%f----%f", _basicanilayer.position.x, _BASICANILAYER.POSITION.Y); Set other animation properties Basicanimation.duration = 2.0; Animation time 2 sec.//basicanimation.repeatcount = Huge_valf; Sets the number of times the animation repeats huge_valf represents infinite, wireless repeat animation//basicanimation.removedoncompletion = NO;              Run once to remove an animation/** * This animation has a problem: the animation after the end of the drawing layer back to the original position, of course, the method of UIView encapsulation is not the problem, how to solve the problem? * The essence of layer animation is to convert the content inside the layer into a bitmap hardware operation to form an animation effect, in fact, the layer itself does not have any changes, the layer in the above animation does not change its position because of the animation effect, (for scaling the animation its size will not change), so after the animation is finished,        There is no change in the properties of the layer, we can reset it after the animation is complete */basicanimation.delegate = self;                Store the current position at the end of the animation using [Basicanimation setvalue:[nsvalue valuewithcgpoint:location] forkey:@ "kcbasicanimationlocation"]; AddAdd animation to the layer, note that key is equivalent to naming the animation, and getting the animation later can use this name to get [_basicanilayer addanimation:basicanimation forkey:@ Kcbasicanimation_            Translation "]; Perform animations in touch-click events} #pragma mark----rotate animation/** * The deformation of the layer is based on the anchor point * Change the anchor point by KeyPath, the center of the rotation is the anchor point of the layer */-(void ) rotationanimation{//1. Creating animations and animating properties cabasicanimation *basicanimation = [Cabasicanimation animationwithkeypath:@ "        TRANSFORM.ROTATION.Y "]; 2.    Set animation property initial value, terminating value Basicanimation.fromvalue = [NSNumber numberwithint:m_pi_2];        Basicanimation.tovalue = [NSNumber numberwithint:m_pi_2 * 3]; 3.    Set other animation Properties Basicanimation.duration = 6.0;        Set rotation and then rotate to the original position basicanimation.autoreverses = true; Basicanimation.repeatcount = Huge_valf;        Set the wireless loop//animation to run once without destroying, default to Yes animation run once directly destroy basicanimation.removedoncompletion = no; Adding animation to a layer key is equivalent to naming the animation, which can be obtained by key [_basicanilayer addanimation:basicanimation forkey:@ "Kcbasicanimation_rotation" ];} /** * Core animations run with the concept of a media time, assuming that a rotation animation setting is rotated for 60 seconds a week,So when the animation rotated 90 degrees, the media time is 15 seconds, if you want to pause the animation only need to let the media time offset set to 15 seconds, and the animation run speed set to 0 let it stop moving, similar, if the 60 wonderful need to restore animation (at this time the media is 75 wonderful), At this point, just set the start time of the animation to the current media time 75 seconds minus the pause time * that is, the offset of the previous stop animation 15 wonderful.    75-15=60 seconds.  In fact, the pause animation and restore animation is the animation speed adjustment, the media time offset and restore the start time setting is mainly to make the animation more consistent.  * */#pragma mark---animation pause-(void) animationpause{//Gets the media time of the specified layer animation, and the following parameter is used to specify the sublayer, which does not require cftimeinterval interval =    [_basicanilayer Converttime:cacurrentmediatime () Fromlayer:nil];    Set the time offset to ensure that the pause stays in the rotation position [_basicanilayer settimeoffset:interval]; Speed set to 0 pause animation _basicanilayer.speed = 0;} #pragma Mark---animation recovery-(void) animationresume{//Gets the media time of the specified layer animation, and the following parameters are used to specify the sublayer, which does not require cftimeinterval interval = Cacurr    Entmediatime ()-_basicanilayer.timeoffset;    Set time offset _basicanilayer.timeoffset = 0;    Set start time _basicanilayer.begintime = interval; Set animation speed, start motion _basicanilayer.speed = 1.0;} #pragma mark----Animation Agent method//When the animation starts-(void) Animationdidstart: (caanimation *) anim{NSLog (@ "animation (%@) Start.\r_layer. frame=%@ ", Anim,Nsstringfromcgrect (_basicanilayer.frame)); A layer called animationforkey:@ "layer set Animation key" NSLog (@ "%@", [_basicanilayer animationforkey:@ "Kcbasic" for animating//animating layers with the key set previously Animation_translation "]);} At the end of the animation-(void) Animationdidstop: (Caanimation *) Anim finished: (BOOL) flag{/** * Another problem is that the animation will be restarted from the start point to the end, the problem          The reason is that, for a non-root view, set the animated properties of the layer (position after the end of the animation, and position is an animated property, which will animate), to solve this problem is to reset the layer's position to close the layer implicit animation * * To turn off implicit animations you need to use the animated transaction catransaction, which closes the implicit animation within a transaction by 1.        Open transaction [catransaction begin];        2. Disable implicit animation [catransaction Setdisableactions:yes];     3. Transaction submission [Catransaction commit];        */NSLog (@ "animation (%@) start.\r_layer.frame=%@", Anim, Nsstringfromcgrect (_basicanilayer.frame));    Open transaction [catransaction begin];        Disable implicit animation [catransaction Setdisableactions:yes];        _basicanilayer.position = [[Anim valueforkey:@ "Kcbasicanimationlocation"] cgpointvalue]; Cabasicanimation *animation = (cabasicanimation *) [Anim Valueforkey:@ "Kcbasicanimation_translation"];    Animation.fromvalue = [Nsvalue valuewithcgpoint:[[anim valueforkey:@ "kcbasicanimationlocation"] CGPointValue]];;        Commit TRANSACTION [Catransaction commit]; Pause animation [self animationpause];}    #pragma mark---Use proxy method drawing-(void) drawrollimageview{//Custom layer Calayer *layer = [[Calayer alloc] init];    Layer.bounds = CGRectMake (0, 0, 150, 150);    Layer.position = Cgpointmake (160, 200); Layer.backgroundcolor = [Uicolor Redcolor].    Cgcolor;        Layer.cornerradius = 150/2;    You need to crop the extra part of the fillet layer.maskstobounds = YES; If you set the effect of the extra picture cropping, you cannot set the shadow of the picture//If you want to set the shadow effect, add a layer and the picture layer, and then set the layer//below the layer is responsible for drawing the shadow, the above layer is responsible for displaying the picture//Note        Meaning: The use of layer deformation to solve the inverted image problem does not need to go DrawRect method//Layer.transform = Catransform3dmakerotation (m_pi, 1, 0, 0);  Note: If you just display a picture in the layer, no need to trouble, directly set the layer contents on//will not be diverted to the drawing, will not be related to inverted problem//set content//UIImage *image = [UIImage imagenamed:@ "Jiqimao"];//[layer setcontents: (ID) image. Cgimage];       Set Layer proxy layer.delegate = self;        Add layer to root layer [self.view.layer addsublayer:layer];        Call Layer Setneeddisplay, otherwise the proxy method will not go [layer setneedsdisplay]; }//layer [Layer Setneedsdisplay] Proxy method Be sure to call this method-(void) Drawlayer: (Calayer *) layer Incontext: (cgcontextref) ctx{//Laye        R is the layer that sets the proxy//cgcontextsavegstate (CTX);    Graphical context deformation to resolve picture handstand problem Cgcontextscalectm (CTX, 1,-1);        CGCONTEXTTRANSLATECTM (CTX, 0,-150);   Uiimageview *imageview = [[Uiimageview alloc] initwithimage:[uiimage imagenamed:@ "Jiqimao"];        Imageview.bounds = CGRectMake (0, 0, 150, 150);       Note that this position is relative to the layer, not the screen cgcontextdrawimage (CTX, cgrectmake (0, 0, Max, max), imageView.image.CGImage);    Cgcontextrestoregstate (CTX);        } #pragma mark draws a circular layer, creating an animation-(void) drawmylayer{cgsize size=[uiscreen mainscreen].bounds.size;    Get root layer Calayer *layer=[[calayer alloc]init]; Set the background color because Quartzcore is a cross-platform framework and cannot be used directly with Uicolor Layer.backgroundcolor=[uicolor colorwithred:0 green:146/255.0 blue:1.0 alpha:1.0].    Cgcolor;    Set Center point Layer.position=cgpointmake (SIZE.WIDTH/2, SIZE.HEIGHT/2);    Set size layer.bounds=cgrectmake (0, 0, width,width);    Sets the fillet, which appears to be a circular layer.cornerradius=width/2 when the radius of the fillet is equal to half the rectangle; Set Shadow Layer.shadowcolor=[uicolor Graycolor].    Cgcolor;    Layer.shadowoffset=cgsizemake (2, 2);    layer.shadowopacity=.9; Set border//Layer.bordercolor=[uicolor Whitecolor].    Cgcolor;        layer.borderwidth=1;        Set Anchor point//Layer.anchorpoint=cgpointzero; [Self.view.layer Addsublayer:layer];}    #pragma mark---Touch method//Click to enlarge the effect-(void) touchesended: (Nsset *) touches withevent: (uievent *) event{//1. Click on Move Animation// Uitouch *touch=[touches anyobject];//calayer *layer=[self.view.layer.sublayers lastObject];//CGFloat width=layer. bounds.size.width;//if (width==width) {//width=width*4;//}else{//width=width;//}//layer.bo Unds=cgrectmake (0, 0, width, width);//Layer.position=[touch Locationinview:self. view];////LAYER.CORNERRADIUS=WIDTH/2; 2.    Basic animation Uitouch *touch = [touches anyobject];            Cgpoint point = [Touch LocationInView:self.view]; Determines if an animation has been created and does not create an animation if it has been created caanimation *animation = [_basicanilayer animationforkey:@ "Kcbasicanimation_translation"]    ;        if (animation) {if (_basicanilayer.speed = = 0) {[Self animationresume];        } else {[self animationpause];                }} else {//Create and start animation [self translationanimation:point];    [Self rotationanimation]; }} @end </span>





IOS coreanimation Basic Animation cabasicanimation

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.