iOS Animation _Core Animation (Core Animation)

Posted by CantonWeb on Fri, 21 Jun 2019 01:15:22 +0200

Introduction

Before, we talked about CALayer and subclass animation, and some attributes of CALayer have implicit animation, which can be viewed independently if you don't understand them. Article Today, let's talk about Core Animation Core Animation.


In the development process, for animation effect, many people seem to prefer UIView animation, simple and fast, a code block can achieve an animation so that many other systems under the development of small partners red-eyed. But when there are some special needs, you will inevitably have a large number of Block nesting, and how to effectively control the animation effect, such as stop animation, control the rhythm of animation and so on will make you unable to start, inevitably the situation shown above. So, in order to brag more smoothly, you may need to understand the core animation Core Animation.


First, let's refresh what you may not know about CALyaer.

Let's look at Layer Tree, a layer hierarchy, which can be divided into three types: Layer Tree, Layer Tree, Layer Tree, Layer Tree, Layer Tree, Layer Tree and Layer Tree.

  • Model Tree: That's what we usually call layer.
  • Presentation Tree: The layer you see when we animate is available through layer. Presentation Layer.
  • Render Tree: Private, inaccessible. The main purpose is to render Presentation Tree data without blocking threads.

Can't you understand? Are you still stubborn? Do you want to be more detailed?



: Don't cut me down. Let's analyze it in detail when we give an example!!!
: At the end of the article, we explain the attribute fields and enumeration values provided by some systems.

Cut into the Theme

Let's look at several categories of core animation:



Let's start with the protocol and class attributes of the above graph and analyze the structure of the above graph.

  • The CAMediaTiming protocol defines time, speed, repetition times and so on. Attributes are defined as follows:
    BeinTime - > is used to set the animation delay. If you want to delay for one second, it is set to CACurrentMediaTime()+1, where CACurrentMediaTime() is the current time of the layer.
    Duration - > duration of animation.
    Speed - > Animation speed, determines the rate of animation time. When speed is 2, the animation time is 1/2 of the set duration.
    Time Offset - > Animation Time Offset. For example, when the time Offset is set to 1.5, the current animation starts from the middle position and skips the first half of the animation before reaching the specified position.
    RepatCount - > Number of repeats of animations.
    Repat Duration - > Repetition Time of Animation.
    Autoreverses - > Animation from the initial value to the final value, whether to return to the initial value of the animation. If set to YES, it means that the animation will return to the initial value in the form of animation.
    Fill Mode - > determines the behavior of the current object during non-animated periods, such as before the animation starts and after the animation ends.
    : Actually, it's not just CAAnimation that follows CAMediaTiming protocol. Small partners who are familiar with the underlying structure should know that CALayer also follows this protocol. To some extent, we can control the rhythm of animation by controlling the protocol attributes of layer itself.

  • CAAnimation Core Animation basic class, can not be used directly. In addition to the methods in CAMediaTiming protocol, the proxy attributes of CAAnimation Delegate are added. Specifically as follows:
    Timing Function - > Control the rhythm of animation. The system provides kCA MediaTiming Function Linear (uniform speed), kCA MediaTiming Function EaseIn (slow in and fast out), kCA MediaTiming Function EaseOut (fast in and slow out), kCA MediaTiming Function EaseIn EaseOut (slow in and slow out, intermediate acceleration), kCA MediaTiming Function Default (default), and of course, CA Mediaing Function can be created by custom.
    Delegate - > Agent.
    Whether removedOnCompletion - > keeps the layer in the state after animation execution, default YES, that is, removing the layer from the coating after animation execution and restoring to the state before animation execution. If NO is set and fillMode is set to kCAFillModeForwards, the state after animation execution is maintained.

  • The animation of CAProperty Animation attributes can not be directly used to set the effect of animation attributes of objects. Add attributes as follows:
    Key Path - > CALayer's attribute name, and through the value of this attribute to modify, to achieve the corresponding animation effect.
    Whether the additive - > attribute animation is based on the current animation effect, the default is NO.
    Cumulative - > specifies whether the animation is cumulative, defaulting to NO.
    ValueFunction - > This attribute is used in conjunction with CALayer's transform attribute.

  • CABasic Animation basic animation is controlled by keyPath corresponding attributes. It needs to set fromValue and toValue. Add the following attributes:
    From Value - > the initial value of the corresponding property of keyPath.
    ToValue - > the end value of the corresponding property of keyPath.
    ByValue - > When toValue is not set, toValue = fromValue + byValue, that is, how much is added to the current position.

  • CASpring Animation has attributes animation with physical parameters such as initial velocity and damping index. We can think of it as a spring tied to a pellet on an imperfectly smooth ground, so we can understand its attributes like this (ask Uncle Newton for physics knowledge):
    Mass - > Ball mass, which affects inertia.
    Stiffness - > stiffness coefficient of spring.
    Damping - > Damping coefficient, ground friction.
    Initial Velocity - > Initial Velocity, which is equivalent to giving the ball an initial velocity (positive or negative, different directions)
    SettlingDuration - > SettlingDuration -> SettlingDuration -> SettlingDuration -> SettlingDuration -> SettlingDuration -> SettlingDuration -> SettlingDuration -> SettlingDuration -> Set

  • The key frame animation of CAKeyFrame Animation is also controlled by keyPath corresponding attributes, but it can be controlled by values or path in many stages. Attributes are as follows:
    An array of values - > key frames, in which each frame is displayed in turn.
    Path - > Key Frame Path, animation elements, priority is higher than values, but only for CALLayer anchor Point and position.
    Key Times - > The corresponding time of each frame, if not set, the key frames are divided equally.
    Timing Functions - > The corresponding animation rhythm for each frame.
    The calculationMode - > Animation calculation mode, the system provides several corresponding modes.
    Tension Values - > Animation Tension Control.
    Continuity Values - > Animation Continuity Control.
    BiasValues - > Animation deviation rate control.
    Rotation Mode - > Animation rotates along the path, the system provides two modes.

  • CATransition animation, the system provides a lot of cool effects. Attributes are as follows:
    Type - > Transit Animation Type.
    Subype - > Transition Animation Direction.
    Start Progress - > Animation Start Progress (overall percentage).
    End Progress - > Animation Endpoint Progress (overall percentage).
    Filter - > Custom Transfer.

  • CAAnimation Group animation group facilitates the unified control and management of multi-animation.
    An array of animations - > all animation effect elements.

CABasicAnimation

In general application development, basic animation can satisfy most of the development needs, mainly completing the animation excess between two values of the specified animation attribute for the object.
The specific process is as follows:

  • Initialize the animation and set the animation keyPath (keyPath is a property name of the CALayer that specifies the animation effect, such as position property)
  • Set other properties of the animation, such as delegate, fromValue, toValue, duration, etc.
  • Use -(void) addAnimation:(CAAnimation*) anim for Key:(nullable NSString*) key; add animation to the specified layer
  • Use -(void) removeAll Animations; or -(void) removeAnimation ForKey:(NSString*) key; methods to stop all or specify animations
    Let's write a simple displacement animation below:
First, create an animated one layer: 
self.aniLayer = [[CALayer alloc] init];
_aniLayer.bounds = CGRectMake(0, 0, 100, 100);
_aniLayer.position = self.view.center;
_aniLayer.backgroundColor = [UIColor redColor].CGColor;
[self.view.layer addSublayer:_aniLayer];
//To generate a CADisplayLink, let's look at the layer s hierarchy we mentioned above:
_displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink:)];
_displayLink.frameInterval = 30;
[_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
//
-(void)handleDisplayLink:(CADisplayLink *)displayLink{
    NSLog(@"modelLayer_%@,presentLayer_%@",[NSValue valueWithCGPoint:_aniLayer.position],[NSValue valueWithCGPoint:_aniLayer.presentationLayer.position]);
}
//When you click on the screen, trigger the animation:
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    CGPoint positon = [touches.anyObject locationInView:self.view];
    [self basicAnimation_PositionTo:positon];
}
//Animation:
-(void)basicAnimation_PositionTo:(CGPoint)position{
    //Initialize the animation and set keyPath
    CABasicAnimation *basicAni = [CABasicAnimation animationWithKeyPath:@"position"];
    //Setting up agents
    basicAni.delegate = self;
    //Location of arrival
    basicAni.toValue = [NSValue valueWithCGPoint:position];
    //Delayed execution
    //basicAni.beginTime = CACurrentMediaTime() + 2;
    //Animation time
    basicAni.duration = 3;
    //Animation Rhythm
    basicAni.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    //Animation Rate
    //basicAni.speed = 0.1;
    //Does the layer show the position and status of the executed animation?
    basicAni.removedOnCompletion = NO;
    basicAni.fillMode = kCAFillModeForwards;
    //Whether the animation returns to the initial value in the form of animation after the completion of the animation
    //basicAni.autoreverses = YES;
    //Animation time offset
    //basicAni.timeOffset = 0.5;
    //Add animation
    [_aniLayer addAnimation:basicAni forKey:NSStringFromSelector(_cmd)];
}

Operation effect:



Print results:

CoreAnimaitonPlayground[3669:389016] modelLayer_NSPoint: {187.5, 333.5},presentLayer_NSPoint: {187.5, 333.5}
CoreAnimaitonPlayground[3669:389016] modelLayer_NSPoint: {187.5, 333.5},presentLayer_NSPoint: {182.1122316699475, 343.44501110725105}
CoreAnimaitonPlayground[3669:389016] modelLayer_NSPoint: {187.5, 333.5},presentLayer_NSPoint: {161.77888754755259, 380.97731033712626}
CoreAnimaitonPlayground[3669:389016] modelLayer_NSPoint: {187.5, 333.5},presentLayer_NSPoint: {128.82425409555435, 441.80661398172379}
CoreAnimaitonPlayground[3669:389016] modelLayer_NSPoint: {187.5, 333.5},presentLayer_NSPoint: {94.108665972948074, 505.88637545704842}
CoreAnimaitonPlayground[3669:389016] modelLayer_NSPoint: {187.5, 333.5},presentLayer_NSPoint: {70.035845696926117, 550.32118600606918}
CoreAnimaitonPlayground[3669:389016] modelLayer_NSPoint: {187.5, 333.5},presentLayer_NSPoint: {61.103064090013504, 566.80975916981697}
CoreAnimaitonPlayground[3669:389016] modelLayer_NSPoint: {187.5, 333.5},presentLayer_NSPoint: {61, 567}
CoreAnimaitonPlayground[3669:389016] modelLayer_NSPoint: {187.5, 333.5},presentLayer_NSPoint: {61, 567}

Here we make a modification:

In animation, we comment out these two lines:
//basicAni.removedOnCompletion = NO;
//basicAni.fillMode = kCAFillModeForwards;

Operation results:



Print results:

CoreAnimaitonPlayground[3710:397153] modelLayer_NSPoint: {187.5, 333.5},presentLayer_NSPoint: {187.5, 333.5}
CoreAnimaitonPlayground[3710:397153] modelLayer_NSPoint: {187.5, 333.5},presentLayer_NSPoint: {187.33332352247089, 333.85210405878024}
CoreAnimaitonPlayground[3710:397153] modelLayer_NSPoint: {187.5, 333.5},presentLayer_NSPoint: {178.31957995891571, 352.89363733679056}
CoreAnimaitonPlayground[3710:397153] modelLayer_NSPoint: {187.5, 333.5},presentLayer_NSPoint: {155.03444194793701, 402.08349138498306}
CoreAnimaitonPlayground[3710:397153] modelLayer_NSPoint: {187.5, 333.5},presentLayer_NSPoint: {121.92566871643066, 472.02577483654022}
CoreAnimaitonPlayground[3710:397153] modelLayer_NSPoint: {187.5, 333.5},presentLayer_NSPoint: {90.934395790100098, 537.49483889341354}
CoreAnimaitonPlayground[3710:397153] modelLayer_NSPoint: {187.5, 333.5},presentLayer_NSPoint: {72.198107242584229, 577.07524845004082}
CoreAnimaitonPlayground[3710:397153] modelLayer_NSPoint: {187.5, 333.5},presentLayer_NSPoint: {187.5, 333.5}

Through the above results and layer level printing, we can confirm that the animation itself does not change the location of model tree, we see that the animation is the trajectory of presentation tree movement. When removedOnCompletion property is set to NO and fillMode property is set to kCAFillModel Forwards, the position of model tree is not changed, but it can prevent presentation tree from being removed and returned to the beginning of the animation after the animation is finished. So it is not recommended to use removedOn Completion with fillMode to achieve the end of the animation, the layer does not jump back to the original implementation, we should reset its position at the beginning or end of the animation.

Next, we use CABasic Animation to achieve several animation effects:

#import "ViewController.h"

#define buttonName @[@ displacement, @ zoom, @ transparency, @ rotation, @ rounded corner]

@interface ViewController ()<CAAnimationDelegate>
@property(nonatomic,strong)CALayer *aniLayer;
//
@property(nonatomic,strong)CADisplayLink *displayLink;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.aniLayer = [[CALayer alloc] init];
    _aniLayer.bounds = CGRectMake(0, 0, 100, 100);
    _aniLayer.position = self.view.center;
    _aniLayer.backgroundColor = [UIColor redColor].CGColor;
    [self.view.layer addSublayer:_aniLayer];
    //
    for (int i = 0; i < 5; i++) {
        UIButton *aniButton = [UIButton buttonWithType:UIButtonTypeCustom];
        aniButton.tag = i;
        [aniButton setTitle:buttonName[i] forState:UIControlStateNormal];
        aniButton.exclusiveTouch = YES;
        aniButton.frame = CGRectMake(10, 50 + 60 * i, 100, 50);
        aniButton.backgroundColor = [UIColor blueColor];
        [aniButton addTarget:self action:@selector(tapAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:aniButton];
    }
    //
//    _displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink:)];
//    _displayLink.frameInterval = 30;
//    [_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}

-(void)tapAction:(UIButton*)button{
    [self basicAnimationWithTag:button.tag];
}

-(void)handleDisplayLink:(CADisplayLink *)displayLink{
    NSLog(@"modelLayer_%@,presentLayer_%@",[NSValue valueWithCGPoint:_aniLayer.position],[NSValue valueWithCGPoint:_aniLayer.presentationLayer.position]);
}

-(void)basicAnimationWithTag:(NSInteger)tag{
    CABasicAnimation *basicAni = nil;
    switch (tag) {
        case 0:
            //Initialize the animation and set keyPath
            basicAni = [CABasicAnimation animationWithKeyPath:@"position"];
            //Location of arrival
            basicAni.byValue = [NSValue valueWithCGPoint:CGPointMake(100, 100)];
            break;
        case 1:
            //Initialize the animation and set keyPath
            basicAni = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
            //Arrival zoom
            basicAni.toValue = @(0.1f);
            break;
        case 2:
            //Initialize the animation and set keyPath
            basicAni = [CABasicAnimation animationWithKeyPath:@"opacity"];
            //transparency
            basicAni.toValue=@(0.1f);
            break;
        case 3:
            //Initialize the animation and set keyPath
            basicAni = [CABasicAnimation animationWithKeyPath:@"transform"];
            //3D
            basicAni.toValue=[NSValue valueWithCATransform3D:CATransform3DMakeRotation(M_PI_2+M_PI_4, 1, 1, 0)];
            break;
        case 4:
            //Initialize the animation and set keyPath
            basicAni = [CABasicAnimation animationWithKeyPath:@"cornerRadius"];
            //fillet
            basicAni.toValue=@(50);
            break;

        default:
            break;
    }

    //Setting up agents
    basicAni.delegate = self;
    //Delayed execution
    //basicAni.beginTime = CACurrentMediaTime() + 2;
    //Animation time
    basicAni.duration = 1;
    //Animation Rhythm
    basicAni.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    //Animation Rate
    //basicAni.speed = 0.1;
    //Does the layer show the position and status of the executed animation?
    //basicAni.removedOnCompletion = NO;
    //basicAni.fillMode = kCAFillModeForwards;
    //Whether the animation returns to the initial value in the form of animation after the completion of the animation
    basicAni.autoreverses = YES;
    //Animation time offset
    //basicAni.timeOffset = 0.5;
    //Add animation
    [_aniLayer addAnimation:basicAni forKey:NSStringFromSelector(_cmd)];
}
//Pause animation
-(void)animationPause{
    //Get the current layer's animation media time
    CFTimeInterval interval = [_aniLayer convertTime:CACurrentMediaTime() toLayer:nil];
    //Set time offset to ensure stay in current position
    _aniLayer.timeOffset = interval;
    //Temporary animation
    _aniLayer.speed = 0;
}
//Recovery animation
-(void)animationResume{
    //Get the pause time
    CFTimeInterval beginTime = CACurrentMediaTime() - _aniLayer.timeOffset;
    //Setting offset
    _aniLayer.timeOffset = 0;
    //Set start time
    _aniLayer.beginTime = beginTime;
    //Start animation
    _aniLayer.speed = 1;
}


#pragma mark - CAAnimationDelegate
-(void)animationDidStart:(CAAnimation *)anim{

}

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end

Operation effect:


CASpringAnimation

CASpring Animation is an animation class introduced by iOS 9. Its effect is similar to UIView spring animation, but it adds the extension of quality, stiffness coefficient and other attributes. It is inherited from CABase Animation and its usage is very simple.

-(void)springAnimation{
    CASpringAnimation *springAni = [CASpringAnimation animationWithKeyPath:@"position"];
    springAni.damping = 2;
    springAni.stiffness = 50;
    springAni.mass = 1;
    springAni.initialVelocity = 10;
    springAni.toValue = [NSValue valueWithCGPoint:CGPointMake(200, 400)];
    springAni.duration = springAni.settlingDuration;
    [_aniLayer addAnimation:springAni forKey:@"springAnimation"];
}

Operation effect:


CAKeyframeAnimation

Key frame animation, like CABasic Animation, is a subclass of CAProperty Animation, but CABasic Animation can only change from one value to another or add an incremental value, while CAKey Frame Animation can set multiple key frames using the values array, and can animate positions or anchors using path. It's also easy to operate:

//Keyframe animation
-(void)keyframeAnimationWithTag:(NSInteger)tag{
    CAKeyframeAnimation *keyFrameAni = nil;
    if (tag == 6) {
        //Wobble
        keyFrameAni = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation"];
        keyFrameAni.duration = 0.3;
        keyFrameAni.values = @[@(-(4) / 180.0*M_PI),@((4) / 180.0*M_PI),@(-(4) / 180.0*M_PI)];
        keyFrameAni.repeatCount=MAXFLOAT;
    }else if (tag == 7){
        //Curve displacement
        keyFrameAni = [CAKeyframeAnimation animationWithKeyPath:@"position"];
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:_aniLayer.position];
        [path addCurveToPoint:CGPointMake(300, 500) controlPoint1:CGPointMake(100, 400) controlPoint2:CGPointMake(300, 450)];
        keyFrameAni.path = path.CGPath;
        keyFrameAni.duration = 1;

    }
    [_aniLayer addAnimation:keyFrameAni forKey:@"keyFrameAnimation"];
}

Operation effect:


CATransition

Transition animation is a transitional effect from one display style to another. It doesn't need much brain to produce cool effects. The system also gives many effects. However, private API should be used cautiously to prevent the tragedy of rejection. Creating transit animation is really simple:

  • Creating Transition Animation
  • Set the type of transition, subtype of self-type (that is, direction of transition, not all effects have subtypes) and other attributes.
  • After setting the new display effect, add animation to the layer.
//Transition animation
-(void)transitionAnimation{
    CATransition *transtion = [CATransition animation];
    transtion.type = @"rippleEffect";
    transtion.subtype = kCATransitionFromLeft;//kCATransitionFromLeft  kCATransitionFromRight
    transtion.duration = 1;
    _transtionIndex++;
    if (_transtionIndex > 4) {
        _transtionIndex = 1;
    }
    _aniLayer.contents = (id)[UIImage imageNamed:[NSString stringWithFormat:@"%@.jpg",@(_transtionIndex)]].CGImage;
    [_aniLayer addAnimation:transtion forKey:@"transtion"];
}

Operation effect:


CAAnimationGroup

In our actual development, we may need more complex complex composite motion, so we need to add more animations to the layer, and the animation group will emerge as the times require. It is also very simple to create animation group. First, create a single animation, then add the created animation group to the animation group, and finally add the animation group to the layer. Don't think of animation poems as a collection of simple animation, because other animation has many attributes, such as timing function, duration, repeatCount, etc. Each element of animation group and animation group can set these attributes separately to achieve a more simple effect than mere combination. (eg: Generate an animation, shake 1 s to the specified position, shake 2 s in place, and then go back to the original position to restart the animation). The code is as follows:

//Animation group
-(void)animationGroup{
    //Rocking animation
    CAKeyframeAnimation *keyFrameAni = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation"];
    keyFrameAni.values = @[@(-(4) / 180.0*M_PI),@((4) / 180.0*M_PI),@(-(4) / 180.0*M_PI)];
    //Each animation can set time and repetition times separately, and control the effect of single animation based on the time of animation group.
    keyFrameAni.duration = 0.3;
    keyFrameAni.repeatCount=MAXFLOAT;
    keyFrameAni.delegate = self;
    //
    //Displacement animation
    CABasicAnimation *basicAni = [CABasicAnimation animationWithKeyPath:@"position"];
    //Location of arrival
    basicAni.byValue = [NSValue valueWithCGPoint:CGPointMake(100, 100)];
    //
    basicAni.duration = 1;
    basicAni.repeatCount = 1;
    //
    basicAni.removedOnCompletion = NO;
    basicAni.fillMode = kCAFillModeForwards;
    //Setting up agents
    basicAni.delegate = self;
    //Animation time
    basicAni.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    CAAnimationGroup *aniGroup = [CAAnimationGroup animation];
    aniGroup.animations = @[keyFrameAni,basicAni];
    aniGroup.autoreverses = YES;
    //The performance time and repetition times of animation are determined by the set of animation group.
    aniGroup.duration = 3;
    aniGroup.repeatCount=MAXFLOAT;
    //
    [_aniLayer addAnimation:aniGroup forKey:@"groupAnimation"];
}

Operation effect:


attach

  • Animation rhythm control property timingFunction:
    CA_EXTERN NSString * const kCAMediaTimingFunctionLinear //Linear uniform velocity
    CA_EXTERN NSString * const kCAMediaTimingFunctionEaseIn //Slow in and fast out
    CA_EXTERN NSString * const kCAMediaTimingFunctionEaseOut //Fast in slow out
    CA_EXTERN NSString * const kCAMediaTimingFunctionEaseInEaseOut  //Slow in and slow out
    CA_EXTERN NSString * const kCAMediaTimingFunctionDefault  //default
    Of course, you can also create the corresponding timingFunction by yourself, and find the way to create it.
  • The current object's behavior fillMode in inactive time:
    CA_EXTERN NSString * const kCAFillModeForwards //After the animation, keep the final state of the animation
    CA_EXTERN NSString * const kCAFillModeBackwards //Get ready before animation begins
    CA_EXTERN NSString * const kCAFillModeBoth  //Before the animation begins, enter the ready state, after the end, keep the final state.
    CA_EXTERN NSString * const kCAFillModeRemoved  //After the animation is completed, remove the default mode
  • valueFunction with transform and the attributes used:
    We do a rotation animation, we will use transform.rotation as keyPath, but it does not really exist, this property is the existence of the system to provide the following way:
    CA_EXTERN NSString * const kCAValueFunctionRotateX
    CA_EXTERN NSString * const kCAValueFunctionRotateY
    CA_EXTERN NSString * const kCAValueFunctionRotateZ
    CA_EXTERN NSString * const kCAValueFunctionScale
    CA_EXTERN NSString * const kCAValueFunctionScaleX
    CA_EXTERN NSString * const kCAValueFunctionScaleY
    CA_EXTERN NSString * const kCAValueFunctionScaleZ
    CA_EXTERN NSString * const kCAValueFunctionTranslate
    CA_EXTERN NSString * const kCAValueFunctionTranslateX
    CA_EXTERN NSString * const kCAValueFunctionTranslateY
    CA_EXTERN NSString * const kCAValueFunctionTranslateZ
    For instance:
    -(void)transformAnimation{
      //Animation revolving around z axis
      CABasicAnimation * transformAni = [CABasicAnimation animationWithKeyPath:@"transform"];
      //Starting at 0 degrees
      transformAni.fromValue = @0;
      //Rotate to 180 degrees
      transformAni.toValue = [NSNumber numberWithFloat:M_PI];
      //duration
      transformAni.duration = 1;
      //Setting valueFunction
      transformAni.valueFunction = [CAValueFunction functionWithName:kCAValueFunctionRotateZ];
      //Add animation
      [_aniLayer addAnimation:transformAni forKey:@"transformAnimation"];
    }
    You can try other values on your own.
  • Attribute animation can be animated by attributes:
    opacity transparency
    backgroundColor background color
    cornerRadius fillet
    borderWidth Border width
    contents content
    shadowColor Shadow color
    shadowOffset Shadow offset
    shadowOpacity Shadow Transparency
    shadowRadius Shadow rounded corners
    ...
    rotation rotate
    transform.rotation.x
    transform.rotation.y
    transform.rotation.z
    ...
    scale zoom
    transform.scale.x
    transform.scale.y
    transform.scale.z
    ...
    translation translation
    transform.translation.x
    transform.translation.y
    transform.translation.z
    ...
    position position
    position.x
    position.y
    ...
    bounds 
    bounds.size
    bounds.size.width
    bounds.size.height
    bounds.origin
    bounds.origin.x
    bounds.origin.y
  • Key frame animation calculation mode:
    When there are multiple key frames, we regard each key frame as a point, then these points can be discrete, can be interpolated after a straight line connection, or can be interpolated after they are connected by a smooth curve. Then we apply this property. The specific values are as follows:
    CA_EXTERN NSString * const kCA Animation Linear default value, the key frames are directly connected to each other for interpolation calculation
     CA_EXTERN NSString * const kCA Animation Discrete is discrete, that is, without interpolation calculation, all key frames are displayed directly one by one.
    CA_EXTERN NSString * const kCA Animation Paced animation proceeds evenly, when keyTimes and timingFunctions settings fail
     CA_EXTERN NSString * const kCA Animation Cubic key frames are used to calculate the interpolation of smooth curves. The shape of curves can also be adjusted and customized by tension Values, continuity Values, bias Values (http://en.wikipedia.org/wiki/Kochanek-Bartels_spline). The main purpose here is to make the trajectory smooth.
    CA_EXTERN NSString * const kCA Animation CubicPaced makes the animation run uniformly on the basis of kCA Animation Cubic, that is, the distance of movement in system time is the same, keyTimes and timing Functions are invalid at this time.
  • The animation rotates along the path in rotation mode, which defaults to nil. The system provides two ways:
    CA_EXTERN NSString * const kCA Animation Rotate Auto rotates along the path
     CA_EXTERN NSString * const kCA Animation Rotate AutoReverse rotates backwards along the path
    It sounds rather difficult to understand. Let's take our previous key frame animation as an example to see a wave of effects.
    Set keyFrameAni.rotationMode = kCAAnimationRotateAuto; the effect is as follows:


Set keyFrameAni.rotation mode = kCAAnimation Rotate AutoReverse; the effect is as follows:


  • Commonly used types of transit animation:


    Direction subtypes include:

epilogue

Have you learned? Go and pretend to be pushed!


Topics: Attribute Spring iOS