The principle and implementation of IOS animation analysis

Source: Internet
Author: User
Tags time 0

This article will not teach you how to achieve a specific animation effect, I will start from the nature of animation, to say the principle of IOS animation and implementation methods.

What is animation

Animation, as the name implies, is able to "move" the painting.
People's eyes have a short memory effect on the image, so when the eyes see multiple images in a continuous, fast switching, it is considered a continuous animation.

For example, the ancient Chinese "merry", is the use of this principle.
Some people will also draw some cartoons on each page of a book, and when they flip quickly, they will see the effect of animation, such as:


Pictures from the implementation of network computer animation

The animation is composed of a picture, in the computer, we call each picture as a frame of the picture.

If we want to achieve such an animation: a water cup on the left side of the table, moving to the right, then we actually operate, just the water Cup.
So the implementation of the animation, only the movement of the parts of the process of change.

Frames-by-frame vs. keyframes

Similar to the above-mentioned hand-painted page, we can find the cup in each frame in the position one by one, so that the animation is called as frame by animation , we need to deal with each frame in the animation.

We generally use FPS on the computer (Frames per Second), that is, the number of frames per second to express the animation refresh rate, based on the screen refresh rates and other reasons, on the computer is generally used by the FPS.
If the motion changes in a relatively slow range, halved to the FPS, we are also acceptable to the naked eye.
The lower FPS will give us a "lag" feeling.

Frames-per-frame animations are the most straightforward, but there are too many frames to process, so the implementation process can be cumbersome.

The work of the computer is to complete the repetitive monotonous work, so, some work can be considered for the computer to complete.

The above example can become a problem involving mathematics and physics: the initial position of a cup on the left, n seconds after the uniform motion to the right, then every 1/60 seconds, the position of the cup is clearly calculated.
So, we just need to specify some key information to allow the computer to calculate the position of each frame of the cup itself:

    • Starting position, such as a coordinate (0,0)
    • End position, another example of a coordinate (100,0)
    • Total animation time, e.g. 0.25 seconds
    • Uniform motion

This approach is called keyframe animation . That is, we only need to give the picture information for several keyframes, and the transition frame between the keyframe and the keyframe will be automatically generated by the computer.

The key frame animation here refers to the generalized animation method, and not only refers CAKeyframeAnimation to CABasicAnimation the implementation of the method also belongs to the key frame animation

IOS Animations

Speaking of the general animation, you can say that IOS animation.
First of all, the essence of animation.

The nature of animation

Continue with the simple example above: An UIView animation that moves from (0,0) to (100,0) at a constant speed, the total animation time is 0.25 seconds.
Suppose we display the animation based on the FPS, then in 0.25 seconds there should be 15 frames, in each frame, the UIView x -coordinate, each time should be moved 100/15 distance.
If we refresh the x-coordinate once every 0.25/15 seconds UIView , we can achieve this animation effect.
For x -coordinates, the position of each frame can be obtained by a function based on the amount of time variation:x=f (t) .

So, the essence of an animation is the state of the animated object (here UIView ), based on the reaction of the time change.
Simply put, you can implement this animation if you can get the position and shape of the animated object at any given moment.
The change in the value of a property can be a change in position, transparency, angle of rotation, etc., as well as changes in shape, such as from a straight line to a circle, and the goal is to get the middle state of a particular moment in the process of change.

Implementation of animations

We can also divide the animation of IOS into two main categories:

    • The system provides the key frame animation realization Way, the user specifies the key information, the system realizes the animation process, is easy for the user to operate.
    • One- frame animation implementation; The user draws each frame picture, the system operation method is simple, but the user operation workload will be bigger.
Step-by-frame animation implementation method

Simply put, to achieve frame-by-frames, it is necessary to periodically call the drawing method, draw each frame animation object.

The painting here is not just a UIView way to redraw the - drawRect: view manually, but also to modify UIView its properties, such as position, color, and so on.

iOS animations are all based on CALayer , and there's UIView a corresponding one behind iOS CALayer . The right UIView changes are actually changes to the CALayer back.
But if a self-built one is modified in a frame-by-picture approach, CALayer this CALayer is not a corresponding one UIView , and you should be aware of the effect of implicit animation of the system, which is mentioned later.

and cyclical , you need a timer to complete, that is CADisplayLink .
CADisplayLinkNSTimersimilar to the comparison, the specified method can be called periodically.
CADisplayLinkThis is used because it is based on the screen refresh rate, which triggers the call every time the screen refreshes.
The IPhone's screen refresh rate is fps.

If the drawing process is too complex to complete within a frame of the screen refresh, consider drawing every other frame, equivalent to the refresh rate of FPS.
Otherwise it may make the animation incoherent, with a sense of Kaka.

The principle of drawing by frame is not very troublesome, the trouble is the drawing process.
For a complex animation, you may need to use a variety of physical and geometric knowledge to calculate the information of the middle State of the view.
For example, to make a straight line curl into a circular animation, you need to calculate the curvature and position of the curve in the middle state.

The famous Facebook pop animation framework is CADisplayLink implemented using this frame-by-frames approach.

How key frame animations are implemented

The use of key frames to achieve animation, the content to speak relative to frame by more than the way.

Or a UIView simple example of moving.
There are two keyframes, starting and ending frames, plus 2 key messages:

    • Start frame, change information: coordinates (0,0)
    • End frame, change information: coordinates (100,0)
    • Animation time, 0.25 seconds
    • Uniform motion

The coordinate information is UIView a property (actually corresponds to CALayer the property), in the animation implementation, we only need to specify the starting and ending of the two key values is enough, the intermediate transition values are automatically generated by the system.
There are two kinds of values here, one for us and one for the system, so we have to insert the concept of a model layer and a presentation layer here first.

CALayerThe same attribute value is stored in the model layer Modellayer , and in the presentation layer Presentationlayer . When we modify the value of the property, it is the value of the model layer that is modified, and the resulting transition value is stored in the presentation layer when the system changes according to the model layer.

In CALayer the object can directly access to these two layers of information.
CALayerthe underlying implementation is actually more than just these two layers, but now we're talking about animations, we can only focus on these two layers.

Throughout the animation process, the process is presented like this:

    1. The current value of the model layer is displayed before the animation;
    2. The animation starts, toggles the display layer value;
    3. In the process of animation, the value of the presentation layer varies according to the time, and what we see is the actual value of the presentation layer changing;
    4. At the end of the animation, switch back to displaying the value of the model layer, at which point the value of the model layer should be modified to the value at the end of the animation.

Use a piece of code to explain the animation process.

    UIView *view = [[UIView Alloc] initWithFrame:CGRectMake (0,0,100,100)]; View. backgroundcolor = [Uicolor Redcolor]; [Self.view Addsubview:view]; cabasicanimation *animation = [CABasicAnimation Animationwithkeypath:@ "position"]; Animation.fromvalue = [nsvalue valueWithcgpoint:cgpointmake (50, 0)]; Animation.tovalue = [nsvalue valuewithcgpoint:cgpointmake (150, 0)]; [View.layer addanimation:animation forkey:nil];//view.frame = Cgrectoffset (view.frame, 0);         

You will find that after the animation view is over, it jumps back to its original position because the last line of code is commented, and the function of this line of code is to implement the 4th step, modifying the value of the model layer to the value at the end of the animation.

Animation implementation

In the code CABasicAnimation is the real part of the animation implementation, which is where the keyframe information is set.

The code that is added to CALayer the animation is defined as:
- (void)addAnimation:(CAAnimation *)anim forKey:(NSString *)key
The accepted type is a CAAnimation type and has the following subclasses:

    • CABasicAnimation, you can set the information for the starting end two keyframes.
    • CAKeyframeAnimation, you can add multiple intermediate keys in addition to the end and end.
    • CAAnimationGroup, you can combine multiple animations because the above two animations can only set one property value at a time.
    • CATransition, the layer transitions animation, which is fade-in by default. For example CALayer , when modifying a background color, the transition from the initial color to the end color fades in.
      Can be modified to the new color to the old color top out and other effects. You can also use CIFilter filters to make transitions, and some open UIViewController -source transition animations Use this approach.

In the animation, in addition to the property values, we also set two time-related information: Animation time 0.25 seconds, the movement is uniform motion.

The duration of the animation is simple and is CAAnimation set by the protocol that follows CAMediaTiming .

Uniform motion is implemented by CAAnimation setting timingFunction , which is the CAMediaTimingFunction object of a class.

As has been said before, the animation process is actually a function of time, the horizontal axis is the change of time value, ordinate is the amount of animation property changes. Then we can draw this function in a Cartesian coordinate system by drawing the graph. For example, the graph of uniform motion is a straight line through the origin point.

So the function of this class is to draw a curve that represents the relationship between time and property changes. The method of drawing is to use the method of drawing Bayesian curve.

The system provides several commonly used functions, such as kCAMediaTimingFunctionLinear uniform motion, kCAMediaTimingFunctionEaseInEaseOut is the default value of the general system animation, fade in and out, that is, at the beginning and end of the animation at a slightly slower speed.


Image source from Network implicit animation

In the process above, we are explicitly CALayer adding an animation to one, so this approach is called explicit animation .
Corresponding, there is implicit animation , that is, the system automatically added on the animation.

 calayer *layer = [calayer layer"; Layer.backgroundcolor = [uicolor greenColor].frame = cgrectmake (0, Span class= "Hljs-number" >0, 100, 100); [self.view.layer AddSublayer : Layer]; Layer.frame = cgrectoffset (layer .frame, 100, 0);     

In this code, we don't add CAAnimation animations, but the layer doesn't change directly to the new position, but has an animated effect.
This is the effect of an implicit animation .

When we change CALayer an animated property value, the implicit animation of the system is triggered.
An animated property value, which can be CALayer found in the document, the attribute description is animatable , and is the property that can be animated automatically.

However, there is an exception, for UIView the underlying CALayer , the system closed the implicit animation, so when we directly modify UIView or its underlying, the CALayer change is directly effective, no animation effect.

So when we animate frames-by-frame, we can directly modify UIView or be the underlying CALayer information.
However, if you modify a self-built individual CALayer , the changes between frames and frames will trigger the default implicit animation of the system, which requires us to manually turn off implicit animation.
This is not noticeable when the animation is fast, but it can obviously lead to a performance waste.

The implicit animation is the same as the display animation, we set the value of the property values are the model layer values, and the system will automatically add the corresponding CAAnimation animation to the CALayer top.

UIViewThere is a series of animateWithDuration animation methods in which the UIView implicit animation is restored, so the implicit animation is triggered when the property is modified in the block of the animation.

So if you know what kind of animation you should add to a property, then you need to get the CAAction protocol up.

When you modify a CALayer property, it queries the action for that - actionForKey: property, and key is the corresponding property name.
CAAnimationFollowing the CAAction agreement, the action returned is actually an CAAnimation animation.
That is, it is CALayer - actionForKey: necessary to invoke which animation to show the change when a property is queried for modification.
By default CABasicAnimation , the default animation time is 0.25 seconds, and the time function is the fade-in kcamediatimingfunctioneaseineaseout.

- actionForKey:There are 4 steps to querying the action, which are described in detail in this method.
One way to do this is CALayer to return to action through the delegate. And for the UIView back of the corresponding CALayer , its agent is its counterpart UIView , UIView is to use this way to close the implicit animation.

Animation transactions

The purpose of creating an animated transaction is to operate atomically, ensuring that all modifications to the animation take effect at the same time.
CATransactionis the action class for the animation transaction.

When creating an implicit animation, the system also implicitly creates an animated transaction to ensure that all animations can be performed at the same time.

In addition, you can explicitly create a transaction.
In an explicit transaction, you can define the run time and time functions of all animations in a transaction, and in addition, this method + (void)setDisableActions:(BOOL)flag can explicitly close the action query operation in the transaction.
When you close the query, the animation effect is turned off, and the change in the property value takes effect immediately, without animation:

    [CATransaction begin];    [CATransaction setDisableActions:YES];    ///...    layer.frame = CGRectOffset(layer.frame, 100, 0); ///... [CATransaction commit];

Be careful not to confuse catransaction with catransition, one word is transaction business, the other is transition transformation.

Comparison summary

The implementation of key frame animation, only need to modify a property value can be, simple and convenient, but involves more deep content, need more understanding and practice.

It is simple to implement the method of frames-by-frame animation, but the process of drawing animation is complicated. If the animation process to deal with more things, it will also bring a large overhead, it is possible to cause the animation frame number of the decline, the phenomenon of lag, so need more testing and debugging.
In the process of animation drawing, more mathematical and physical knowledge is required to calculate the data of the intermediate state.

But neither of these approaches is absolutely separate.
The implementation of key frame animation, in general, can only be animated by the system to animate the properties, but it is also allowed to implement the custom properties of animation processing.
This requires that the system automatically calculate the transition frame operation, that is, the way to achieve animation by frame.
Animations that implement custom properties can be referenced in this article: Animating custom properties in a Layer

For the IOS system provided by the animation method, the above only from the overall perspective of a comprehensive collation, there are many details are not written out, such as CALayer three-dimensional transformation, CAKeyframeAnimation the delay path animation, CAMediaTiming the time control, and so on. If you are interested, you can take a look at these items:

    • Apple Official document Core Animation Programming Guide
    • IOS Core animation:advanced Techniques--Chinese translation
    • OBJC animation interpretation in the special topic of Chinese animation

The principle and implementation of IOS animation analysis

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.