The basic concept

What is core animation

Core Animation is a set of powerful and gorgeous Animation APIS, which are widely used in iOS systems and apps you develop. The location of the core animation is shown below:





Core Animation.png

As you can see, the core animation is one layer below UIKit, and it can achieve more complex animation effects than UIView animation.

The Core animation layer acts on a CALayer (Core Animation Layer). A CALayer is conceptually similar to a UIView, which we can think of as a special kind of CALayer (that can respond to events). In fact, each view has a corresponding layer, which is the root layer:

    @property(nonatomic.readonly.strong)                 CALayer  *layer;Copy the code

Animating a view is essentially an operation on its layer, which contains the properties that support animation, and the animation contains the value of the property change, the speed of change, the time of change, etc. The combination of the two generates animation.

Comparison between core animation and UIView animation: UIView animation can be regarded as the encapsulation of core animation. Different from UIView animation, the state of layer (such as position) is changed by core animation, which actually remains unchanged after the animation is executed (it looks changed on the surface).

Overall, the advantages of core animation are as follows:

1) Powerful performance, using hardware acceleration, can add different animation effects to multiple layers at the same time 2) easy interface, only need a small amount of code to achieve complex animation effects. 3) Run in the background thread, can respond to interactive events during animation (UIView animation does not respond to interactive events during animation by default).

2. Hierarchy of core animation classes




Core Animation classes and protocol.png

CAAnimation is the parent class of all animation objects, CAMediaTiming protocol, responsible for the control of animation time, speed and time curve, etc., is an abstract class, can not be used directly. CAPropertyAnimation: a subclass of CAAnimation that animates the layer’s keyPath. CASpringAnimation is a subclass of CABasicAnimation that implements spring animation after iOS9.0.

To sum up, the core animation class can be directly used in the following classes:

CABasicAnimation CAKeyframeAnimation CATransition CAAnimationGroup CASpringAnimation

3. Core method of core animation class

1. Initialize CAAnimation objects. Generally, animation method is used to generate instances

     + (instancetype)animation;Copy the code

If it is a subclass of CAPropertyAnimation, you can also generate instances using animationWithKeyPath

     + (instancetype)animationWithKeyPath:(nullable NSString *)path;Copy the code

2. Set animation properties. Set animation execution time, execution curve, keyPath target value, agent, etc

Call CALayer’s addAnimation:forKey: method to add the animation to CALayer, and the animation will begin execution

     - (void)addAnimation:(CAAnimation *)anim forKey:(nullable NSString *)key;Copy the code

Call CALayer’s removeAnimation method to stop the animation in CALayer

     - (void)removeAnimationForKey:(NSString *)key;
     - (void)removeAllAnimations;Copy the code
4. Common properties of core animation classes

KeyPath: You can specify keyPath as the CALayer property value and modify its value to achieve the corresponding animation effect. Note that some of the properties do not support animation effect. The following keyPath is animated:

     //CATransform3D Key Paths : (example)transform.rotation.z
     //rotation.x
     //rotation.y
     //rotation.z
     / / rotation rotation
     //scale.x
     //scale.y
     //scale.z
     / / scale zooming
     //translation.x
     //translation.y
     //translation.z
     / / translation translation

     //CGPoint Key Paths : (example)position.x
     //x
     //y

     //CGRect Key Paths : (example)bounds.size.width
     //origin.x
     //origin.y
     //origin
     //size.width
     //size.height
     //size

     //opacity
     //backgroundColor
     //cornerRadius 
     //borderWidth
     //contents 

     //Shadow Key Path:
     //shadowColor 
     //shadowOffset 
     //shadowOpacity 
     //shadowRadiusCopy the code

Duration: duration of animation repeatCount: number of animation repeats timingFunction: time and rhythm control of animation

The timingFunctionNameenumValues are as follows:KCAMediaTimingFunctionLinear uniform kCAMediaTimingFunctionEaseIn into kCAMediaTimingFunctionEaseOut slow out slow KCAMediaTimingFunctionEaseInEaseOut slow in slow out kCAMediaTimingFunctionDefault default values (slow in slow out)Copy the code

FillMode: Indicates the view’s behavior when it is not Active. RemovedOnCompletion: Default is YES (the view will be restored to its pre-animation state). Optionally set to NO (the layer will remain at its post-animation state provided fillMode is set to kcafillmodeforward). Animation latency (CACurrentMediaTime() + Your time) delegate: delegate

Proxy methods are as follows: - (void)animationDidStart:(CAAnimation *)anim;  // Start animation
     - (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag; // End of animationCopy the code

CABasicAnimation

The CABasicAnimation can set the start and end values of the keyPath. The animation moves along the set point. The CABasicAnimation can be considered as a special CAKeyFrameAnimation with only two key points.

The following uses position to change a view as an example:

- (void)position {
    CABasicAnimation * ani = [CABasicAnimation animationWithKeyPath:@"position"];
    ani.toValue = [NSValue valueWithCGPoint:self.centerShow.center];
    ani.removedOnCompletion = NO;
    ani.fillMode = kCAFillModeForwards;
    ani.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [self.cartCenter.layer addAnimation:ani forKey:@"PostionAni"];
}Copy the code

Animation effect:





position.gif

Here are some of the keyPath animations (the image name corresponds to the keyPath) :





positionX.gif





positionY.gif





rotation.gif





rotationX.gif





rotationY.gif





rotationZ.gif





scale.gif





translation.gif





The combined effect of transform.gif





bounds.gif





size.gif





sizeW.gif





sizeH.gif





opacity.gif





backgroundColor.gif





cornerRadius.gif





borderWidth.gif





contents.gif





shadowColor.gif





shadowOffset.gif





shadowOpacity.gif





shadowRadius.gif

CAKeyframeAnimation

You can set the keyPath starting point, the middle key point (more than one), the value of the end point, the time for each frame, and the animation will move along the set point.

Important properties of CAKeyframeAnimation:

Values: keyframe array object, in which each element is a keyframe, animation will execute each keyframe animation in the corresponding period of time. Path: Animation path object that can specify a path that will be moved during animation execution. Path only affects the Position of the view in the animation. KeyTimes: sets the time point corresponding to a key frame. The value ranges from 0 to 1. If this property is not set, the time of each frame is evenly split.

To demonstrate its use, let the view loop as an example:

1. Set values to move along the square
- (void)valueKeyframeAni {
    CAKeyframeAnimation * ani = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    ani.duration = 4.0;
    ani.removedOnCompletion = NO;
    ani.fillMode = kCAFillModeForwards;
    ani.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    NSValue * value1 = [NSValue valueWithCGPoint:CGPointMake(150.200)];
    NSValue *value2=[NSValue valueWithCGPoint:CGPointMake(250.200)];
    NSValue *value3=[NSValue valueWithCGPoint:CGPointMake(250.300)];
    NSValue *value4=[NSValue valueWithCGPoint:CGPointMake(150.300)];
    NSValue *value5=[NSValue valueWithCGPoint:CGPointMake(150.200)];
    ani.values = @[value1, value2, value3, value4, value5];
    [self.centerShow.layer addAnimation:ani forKey:@"PostionKeyframeValueAni"];
}Copy the code

Animation effect:





valueKeyframeAni.gif

2. Set path to go in a circle
- (void)pathKeyframeAni {
    CAKeyframeAnimation * ani = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    CGMutablePathRef path = CGPathCreateMutable(a);CGPathAddEllipseInRect(path, NULL.CGRectMake(130.200.100.100));
    ani.path = path;
    CGPathRelease(path);
    ani.duration = 4.0;
    ani.removedOnCompletion = NO;
    ani.fillMode = kCAFillModeForwards;
    [self.centerShow.layer addAnimation:ani forKey:@"PostionKeyframePathAni"];
}Copy the code

Animation effect:





pathKeyframeAni.gif

CATransition

Transitions have more animation effects than UIVIew transitions. For example, Nav’s default Push view is implemented through the kCATransitionPush type of CATransition.

Important properties of CAKeyframeAnimation:

Type: Indicates the type of transition animation

    typetheenumValues are as follows:KCATransitionFade Gradient kCATransitionMoveIn overlay kCATransitionPush push kCATransitionReveal revealCopy the code

There are also private animation types that are cool, but not recommended. Private animation types include: “cube”, “suckEffect”, “oglFlip”, “rippleEffect”, “pageCurl”, “pageUnCurl”, etc.

Subtype: Direction of transition animation

Subtype ofenumValues are as follows:KCATransitionFromRight kCATransitionFromLeft kCATransitionFromTop kCATransitionFromBottomCopy the code

Take gradients for example

- (void)transitionAni {
    CATransition * ani = [CATransition animation];
    ani.type = kCATransitionFade;
    ani.subtype = kCATransitionFromLeft;
    ani.duration = 1.5;
    self.centerShow.image = [UIImage imageNamed:@"Raffle"];
    [self.centerShow.layer addAnimation:ani forKey:@"transitionAni"];
}Copy the code

Animation effect:





kCATransitionFade.gif

Here are the animation effects for the other three transition types (the image name corresponds to its Type) :





kCATransitionMoveIn.gif





kCATransitionPush.gif





kCATransitionReveal.gif

Here are some animations of the private transition types (the image name corresponds to its Type) :





transitionAni – rippleEffect.gif





transitionAni – cube.gif





transitionAni – pageCurl.gif





transitionAni – suckEffect.gif

CASpringAnimation

CASpringAnimation is a new animation type added in iOS9. It is a subclass of CABasicAnimation and is used to realize spring animation.

Important attributes of CASpringAnimation:

The greater the mass, the greater the inertia of the spring, the greater the amplitude of movement. If the initial speed is 0, it means that this property is ignored. SettlingDuration: The time from the start of the spring to the end of the spring. The best time to set the animation time is based on this time.

Compare CASpringAnimation with UIView’s SpringAnimation:

1.CASpringAnimation can set more properties that affect the animation effect of springs, achieve more complex animation effects of springs, and can be combined with other animations. 2. The SpringAnimation of UIView is actually realized by CASpringAnimation.

Take the example of a spring animation that implements a view’s bounds change:

- (void)springAni {
    CASpringAnimation * ani = [CASpringAnimation animationWithKeyPath:@"bounds"];
    ani.mass = 10.0; // Mass, which affects the inertia of the spring as the layer moves. The greater the mass, the greater the stretch and compression of the spring
    ani.stiffness = 5000; // Stiffness coefficient (stiffness coefficient/elastic coefficient), the greater the stiffness coefficient, the greater the force generated by the deformation, the faster the movement
    ani.damping = 100.0; // The damping coefficient, which prevents the spring from stretching, the greater the damping coefficient, the faster it stops
    ani.initialVelocity = 5.f; // Initial speed, the initial speed of the animated view; When the speed is positive, the direction of velocity is consistent with the direction of motion; when the speed is negative, the direction of velocity is opposite to the direction of motion
    ani.duration = ani.settlingDuration;
    ani.toValue = [NSValue valueWithCGRect:self.centerShow.bounds];
    ani.removedOnCompletion = NO;
    ani.fillMode = kCAFillModeForwards;
    ani.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [self.cartCenter.layer addAnimation:ani forKey:@"boundsAni"];
}Copy the code

Animation effect:





springAni.gif

CAAnimationGroup

Groups can be used to combine multiple animations into a layer. All animations in a Group are executed concurrently, making it easy to achieve scenes that require multiple types of animations.

Take the combined animation that implements position, bounds, and opacity changes on a view

- (void)groupAni {
    CABasicAnimation * posAni = [CABasicAnimation animationWithKeyPath:@"position"];
    posAni.toValue = [NSValue valueWithCGPoint:self.centerShow.center];

    CABasicAnimation * opcAni = [CABasicAnimation animationWithKeyPath:@"opacity"];
    opcAni.toValue = [NSNumber numberWithFloat:1.0];
    opcAni.toValue = [NSNumber numberWithFloat:0.7];

    CABasicAnimation * bodAni = [CABasicAnimation animationWithKeyPath:@"bounds"];
    bodAni.toValue = [NSValue valueWithCGRect:self.centerShow.bounds];

    CAAnimationGroup * groupAni = [CAAnimationGroup animation];
    groupAni.animations = @[posAni, opcAni, bodAni];
    groupAni.duration = 1.0;
    groupAni.fillMode = kCAFillModeForwards;
    groupAni.removedOnCompletion = NO;
    groupAni.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [self.cartCenter.layer addAnimation:groupAni forKey:@"groupAni"];
}Copy the code

Animation effect:





groupAni.gif

CATransaction

Finally, transactions. Within the core animation, there is the concept of a transaction (CATransaction), which is responsible for coordinating multiple animated atom update display operations. To put it simply, transaction is a basic unit in core animation. Animation is inevitably accompanied by the change of layer Animatable property, and the change of layer property must belong to a transaction. Therefore, the core animation relies on transactions.

Transactions can be classified into implicit and explicit: 1. Implicit: A method that does not obviously invoke a transaction and is automatically generated by the system. For example, setting the Position property of a layer will automatically generate a transaction in the current thread and commit the transaction in the next runLoop. 2. Explicit: methods that explicitly call the transaction ([CATransaction begin] and [CATransaction commit]).

Settable properties of CA transactions (which override Settings for implicit animation) :

AnimationDuration: animationTimingFunction: Animation time curvedisableActions: Whether to close the animation completionBlock: callback to the animation completionCopy the code

Transactions support nested use: animation starts when the outermost transaction is committed.

Example:

    [CATransaction begin];
    [CATransaction setAnimationDuration:2.0];
    [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
// [CATransaction setDisableActions:YES]; // Set to YES to close animation
    self.subLayer.bounds = self.centerShow.layer.bounds;
    [CATransaction commit];Copy the code

Note: only the root layer have an implicit animation, if you are directly set self. CartCenter. Layer. The bounds = self. CenterShow. Layer. The bounds; There will be no animation.

Next

Next up is an update to the iOS drawing engine Quartz2D