0. Preface
There's not much code detail here, just exploring the basic concepts of iOS animations, as well as its abstract models, mathematical foundations and so on. When we learn a knowledge, there are generally two parts, abstract parts and image parts, abstraction is like the grammar of language, is the rule, the image is like the concrete sentence, Can be used to communicate with others. Abstraction is harder to understand than image, but more common than image. In fact, mathematics often encounter abstract and image of the concept, such as a series of discrete points, this is the image; Through these points we fit a curve, get its function, the function is abstract, then through this function we can get more points, This is back to the image. So learning any knowledge can not just stay in the will use, but to rise to a level, to learn the knowledge of its abstraction level, the higher the level of abstraction, the more general.
I. Basic CONCEPTS
What is Animation (animation), simple point is that in a period of time, the content of the display has changed. For Calayer, the Animatable property has changed over time. from Calayer (CA = Core Animation Class name, you can see that the layer of iOS is animated for a good interactive experience. Here are two things: one is layer (base class Calayer) and one is animation (based on Caanimation). Animation acts on Layer.calayer provides an interface for adding animation to itself. The layer used for the display is essentially a model that contains the various property values of the layer. The animation contains the time, variation, and speed of the animation. The following is a detailed explanation of the layer and animation related knowledge.
Two. Calayer and time model
We all know that UIView is the view.uiview of MVC. The responsibility lies in the display of interfaces and the handling of interface events. Each view has a layer behind it (accessed through View.layer), and the layer is used for the interface display. Calayer belongs to the Quartzcore framework, which is very important, but not as well understood as imagined. The layer that we typically manipulate to display is the role of the data model in the concept of the core animation. It does not directly do rendering work. About layer, which was previously analyzed from the point of view of the coordinate system, this time it is focused on its temporal systems.
1.Layer Rendering Architecture
Layer also has a hierarchical tree structure like view, called the layer tree, which is created directly or obtained through UIView (View.layer) for the display of the layer tree, called the Model tree, There are also two copies of the layer tree behind the model tree, one for the Presentation tree and one for the render tree. The rendering tree can be obtained from the layer.presentationlayer of the normal layer (which is actually the model tree), while the model tree can be obtained through the Modellayer attribute (detail document). The properties of the model tree become new values as they are modified. This is the part that can be manipulated directly by the code, and the property values of the rendering tree are consistent with those seen on the interface during the animation. While the render tree is private and you cannot access it, the render tree renders the data of the rendering tree, in order not to block the main thread, the rendering process is performed in a separate process or thread, So you'll find that animation animations don't block the main thread.
2. Transaction Management
Calayer's (animatable) attributes, called animatable Properties, have a list of the details, listing all Calayer animatable properties. If a layer object has a corresponding view, the layer is called a root layer, and the non-root layer is typically created directly from Calayer or its subclasses. The following sublayer is a typical non-root layer, It does not have a corresponding view object associated with it.
Sublayer=[[CalayerAlloc] init; sublayer. Frame = cgrectmake (0 0300300sublayer. BackgroundColor = [[uicolor redcolor ] cgcolor; [self. View. Layer addsublayer:sublayer];
All non-root layers have implicit animations when setting animatable properties, and the default duration is 0.25 seconds.
subLayer.position = CGPointMake(300,400);
Like the above code, the next time a runloop start is not directly to the sublayer position into (300,400), but a moving animation to complete the transition.
Any setting of the Animatable property of a layer should belong to a CA transaction (catransaction), and the purpose of the transaction is to ensure that multiple animatable attributes are changed at the same time, whether it is between the same layer or a different layer. Catransaction is also divided into two categories, explicit and implicit, when a animatable attribute is set in a Runloop, a CA transaction is automatically created if no transaction is found, and the transaction is automatically commit when the next runloop of the thread starts. , you must use an explicit transaction if you set the Animatable property of the layer in a place where there is no runloop.
The use of an explicit transaction is as follows:
[CATransaction begin];... [CATransaction commit];
Transactions can be nested. When a transaction is nested, the entire animation starts only when the outermost transaction commits.
You can set a transaction-level animation property through Catransaction, overriding the related properties of an implicit animation, such as a duration that overrides an implicit animation, Timingfunction. If the explicit animation is not set duration or timingfunction, then these parameters of the CA transaction settings will also work on this explicit animation.
You can also set Completionblock, Completionblock is called when all the animation for the current catransaction finishes.
3. Time System
The
Calayer implements the Camediatiming protocol. Calayer implements a hierarchical time system through the Camediatiming protocol. In addition to Calayer,caanimation also adopted this protocol, the time system used to implement animation.
in the CA, there is a absolute The time (absolute time) concept can be obtained by Cacurrentmediatime (), in fact, this absolute time is the value of converting mach_absolute_time () into seconds. This is about the uptime of the system, Cacurrentmediatime () will be reset after the system restarts. the
has the same relative coordinates as the coordinates, and different objects that implement the hierarchical relationship of the Camediatiming protocol also have relative time, which often requires time conversion. Calayer provides two time-conversion methods:
- (CFTimeInterval)convertTime:(CFTimeInterval)t fromLayer:(CALayer *)l;- (CFTimeInterval)convertTime:(CFTimeInterval)t toLayer:(CALayer *)l;
Now focus on several important attributes of the camediatiming protocol.
BeginTime
Whether it is a layer or an animation, there is a concept of timeline timeline, and their begintime is the start time relative to the parent object. Although not indicated in Apple's documentation, it can be found through code testing that all Calayer layers have a consistent timeline by default, their begintime are 0, and absolute time is the size of the absolute time that is converted to the current layer. So for a layer, Although they are created successively, their timelines are consistent (as long as they are not actively modifying the begintime of a layer), so we can imagine that all layers default to the timing of their timelines starting after the system restarts.
But the time line of the animation is different, when an animation is created, added to a layer, it will be copied to join the current layer, when the CA transaction is committed, if the begintime of the animation in the layer is 0, The begintime is set to the current time of the current layer, which causes the animation to start immediately. If you want an animation that is directly added to the layer to be executed later, you can manually set the animation's begintime, but note that this begintime needs to be Cacurrentmediatime () + delayed number of seconds, because BeginTime refers to a time on the timeline of its parent object, at which point the parent object of the animation is the layer that is added, and the current time of the layer is actually [layer convertTime: Cacurrentmediatime () Fromlayer:nil], in fact, is equal to Cacurrentmediatime (), then the time line on this layer delay a certain number of seconds to get the above results.
Timeoffset
This timeoffset may be one of the more difficult to understand in these properties, and the official documentation is not very clear. Local time is also divided into two types: active local time, which is the basic local time.
The Timeoffset is the offset of the active local time.
You think of an animation as a ring, timeoffset change is actually the beginning of the animation in the ring, such as a duration for 5 seconds of animation, the Timeoffset is set to 2 (or 7, modulo 5 is 2), then the animation runs from the original 2 seconds to 5 seconds, Then 0 seconds to 2 seconds to complete the animation.
Speed
The Speed property is used to set the time flow of the current object relative to the time flow of the parent object, such as an animation begintime is 0, but the velocity is 2, then this animation is equivalent to 1 seconds of the parent object in the time stream of 2 seconds. The larger the speed, the faster the time goes, the faster the animation. For example, a layer of 2 for all of its fathers was 1, and it had a sublayer,speed of 2, Then a 8-second animation runs in this sublayer in just 2 seconds (8/(2 * 2)). So speed has an overlay effect.
Fillmode
Fillmode's role is to determine the behavior of the current object over a non-active time period. For example, before the animation starts, after the animation ends. If it is an animated caanimation, you need to set its removedoncompletion to No, otherwise fillmode will not work. Here's what each fillmode means.
Kcafillmoderemoved This is the default value, that is, when the animation starts and after the end of the animation, the animation has no effect on the layer, the end of the animation, the layer will revert to the previous state
Kcafillmodeforwards when the animation is finished, the layer will remain the last state of the animation
Kcafillmodebackwards This is relative to Kcafillmodeforwards, that is, before the animation starts, you just add the animation to a layer,layer and immediately enter the initial state of the animation and wait for the animation to begin. You can set the test code like this, A delay of 5 seconds is performed when an animation is added to a layer. And then you'll find that when the animation is not started, the animation is in the initial state as long as it is added to the Layer,layer.
Kcafillmodeboth understand the above two, this is very good understanding, this is actually the above two synthesis. Before the animation joins, the layer is in the initial state of the animation, and the layer retains the last state of the animation after the animation is finished.
Some of the other parameters are relatively easy to understand.
Practical application
See Apple official QA1673 How to pause the animation of a layer tree
-(void)Pauselayer:(Calayer*)Layer{CftimeintervalPausedtime=[LayerConvertTime:Cacurrentmediatime()Fromlayer:Nil];Layer.Speed=0.0;Layer.Timeoffset=Pausedtime;}-(void)Resumelayer:(Calayer*)Layer{CftimeintervalPausedtime=[LayerTimeoffset];Layer.Speed=1.0layer. Timeoffset = 0.0layer. BeginTime = 0.0cftimeinterval timesincepause = [ Layer converttime:cacurrentmediatime () Fromlayer:nil -pausedtimelayer. BeginTime = timesincepause;}
Three. Explicit animation animation
When you need to animate a non-root layer or need to do more customization of the animation, you must use explicit animation, the base class of the explicit animation is caanimation, commonly used is cabasicanimation, Cakeyframeanimation sometimes use caanimationgroup,catransition (note that catransaction,transition is not the meaning of transition).
Here we emphasize two important points about animation: one is the interpolation calculation of the middle State (interpolation), the other is the animation Rhythm control (Timing); Sometimes the interpolation calculation also has a certain relationship with timing. If the state is a value of one-dimensional space (such as transparency), then the result of the interpolation calculation must be between the starting value and the end value, if the state is a two-dimensional space value (such as position), then generally the point of interpolation will fall on the line between the starting point and the end point (of course, it is possible that the lines
1.CABasicAnimation
Whether cabasicanimation or Cakeyframeanimation are inherited from Capropertyanimation.cabasicanimation, there are three more important attributes, Fromvalue,tovalue, Byvalue, these three properties are optional, but cannot be more than two non-empty at the same time. Ultimately, to determine the start and end of the animation change. Setting interpolation values details the various scenarios and uses of this three value. After you set the start and end of the animation, the values in the middle are calculated by interpolation. The result of the interpolation calculation is specified by Timingfunction, and the default timingfunction is nil, which uses liner, that is, the change is uniform.
The function of 2.Timing function
The Timing function is used to calculate the interpolation between the starting and ending points of the change. The image point is that Timing function determines the rhythm of the animation (pacing), such as the uniform change (same time change the same amount), first fast after slow, first slow or fast or slow before the slow.
The time function is the use of a function to describe, the horizontal coordinates is the time t value range is 0.0-1.0, the longitudinal coordinates is the change of the amount of X (t) is also the range of values also 0.0-1.0 assume that there is an animation, duration is 8 seconds, the starting point of the change value is a end is B (assuming transparency), So what's the value in 4 seconds? It can be calculated as A + x (4/8) * (B-A), why is this calculated? When the implementation time is mapped to the unit value of 4 seconds relative to the total time 8 seconds is 0.5 then can get 0.5 when the unit change is x (0.5), X (0.5)/1 = actual change amount/(B-a), where b-a is the total change, so the actual change is x (0.5) * (B-A), The value of the last 4 seconds is a + x (0.5) * (B-A), so the essence of the calculation is mapping.
The class of the Timing function corresponds to Camediatimingfunction, which provides two ways to obtain the time function, one is to use the predefined five time functions, and one is to get a time function by giving the point two control points. The relevant method is
+(Id)Functionwithname:(NSString*)Name;+(Id)Functionwithcontrolpoints:(Float)C1x:(Float) c1y : (float) span class= "n" >c2x : (float) c2y< Span class= "P"; - (idinitwithcontrolpoints:< Span class= "P" > (float) c1x : ( Span class= "kt" >float) c1y : () c2x : (float ) c2y
The constant quantity of the five predefined time function names is
Kcamediatimingfunctionlinear,
Kcamediatimingfunctioneasein,
Kcamediatimingfunctioneaseout,
Kcamediatimingfunctioneaseineaseout,
Kcamediatimingfunctiondefault.
Show the preceding four kinds of timing function, the horizontal coordinates indicate the time, the longitudinal coordinates indicate the change amount, this need to be clear (not in the plane coordinate system xy).
The functional image of a custom timing function is a three-time Bezier curve cubic Bézier Curve, the advantage of the Bezier curve is smooth, which makes the change appear smooth. A three-time Bezier curve can be determined by the starting point and two control points.
The corresponding function curve of the above kcamediatimingfunctiondefault is actually through [(0.0,0.0), (0.25,0.1), (0.25,0.1), (1.0,1.0)] These four points determine the three times Bezier curve, The beginning and end of the line is the starting point and the center point.
P0 is the starting point, P3 is the end point, P1 and P2 are two control points
If the time-varying curve is neither a straight line nor a Bezier curve, but a custom one, or if the trajectory of a layer's motion is not a straight line but a curve, these are the basic animations that cannot be done, so the introduction of the following content, Cakeyframeanimation, is also known as Keyframe animation.
3.CAKeyframeAnimation
Any animation to show motion or change requires at least two different critical states, while changes in the middle state can be done by interpolation, resulting in a motion tween, a frame that represents a critical state is called a keyframe. Cabasicanimation can actually be seen as a special keyframe animation, with only two keyframes. Cakeyframeanimation can support any number of keyframes, keyframes are specified in two ways, using path or using Values,path is a cgpathref value, and path can only Calayer Anchorpoint and The Position property works, and the values are no longer valid after the path is set. And values are more flexible. Keytimes This optional parameter can specify a corresponding point in time for the corresponding keyframe, with a value ranging from 0 to 1.0,keytimes each time value corresponds to each frame in values. When the keytimes is not set, the time of each keyframe is equally divided.
You can also set timingfunction for transitions between keyframes by setting the optional parameter Timingfunctions (Timingfunction is not valid in cakeyframeanimation). If values have n elements, then timingfunctions should have n-1. But most of the time do not need to timingfunctions, because there are enough keyframes have been set, such as not 1/60 seconds set a key frame, then the frame rate will reach 60FPS , there is no need to transition between two frames at all (it is also possible that a two frame value is a large distance, you can use a uniform change or increase the frame rate, such as setting a keyframe every 0.01 seconds).
There is also a very important parameter in the Keyframe animation, which is Calculationmode, the calculation mode. It is mainly for the contents of each frame as a block punctuation, that is, to anchorpoint and position Animation. When there are multiple discrete points in a planar coordinate system, they can be discrete, or they can be interpolated after straight lines, or they can be interpolated using a sleek curve. Calculationmode currently offers several modes Kcaanimationlinear
Kcaanimationdiscrete
kcaanimationpaced
Kcaanimationcubic
kcaanimationcubicpaced
The default value of Kcaanimationlinear Calculationmode, which means that when keyframes are block punctuation, the direct straight line between keyframes is interpolated to calculate the interpolation value;
Kcaanimationdiscrete discrete, is not the interpolation calculation, all the key frames are displayed directly;
Kcaanimationpaced make the animation evenly, not by keytimes set or by key frame split time, at this time keytimes and timingfunctions invalid;
Kcaanimationcubic interpolation calculation for key frames with key frames as block punctuation, and for curve shape can be adjusted by tensionvalues,continuityvalues,biasvalues, The mathematical principle here is kochanek–bartels spline, where the main purpose is to make the running trajectory become smooth;
kcaanimationcubicpaced see this name to know and Kcaanimationcubic have a certain connection, in fact, is on the basis of Kcaanimationcubic make the animation run evenly, is the system time within the same distance movement, Keytimes and timingfunctions are also invalid at this time.
Finally recommend the next WWDC 2010 and 2011 on the animation related session, you can look for it. 2010 of the core graphic related content. And they all interpret the CA in terms of performance.
Good article had to turn around: Turn from: http://geeklu.com/2012/09/animation-in-ios/
Talk about iOS Animation