Core Animation Advanced Theoretical Knowledge Summary

Source: Internet
Author: User
Tags cos

First, the basic concept

Core animation is actually a misleading designation. You might think it's just for animation, but it actually evolved from a little animated name called Layer Kit, so animating this is just the tip of the core animation feature. Core animation is a composite engine whose job is to combine different visual content on the screen as quickly as possible, which is decomposed into separate layers and stored in a system called a layer tree. So this tree forms the basis for uikit and everything you can see on the screen in an iOS app. the biggest difference with UIView is that Calayer does not handle user interactions, and Calayer is not aware of the specific response chain (the mechanism by which iOS transmits touch events through a view-level relationship), so it does not respond to events. Each uiview has a layer property of a Calayer instance, so-called backing layer[a view has only one associated layer (created automatically), and it can also support adding countless sublayers], The responsibility of the view is to create and manage this layer to ensure that when the sub-views are added to or removed from the hierarchy, their associated layers also correspond to the same actions in the hierarchical tree. In addition to the view level and the layer tree, there are rendering trees and render trees, and here are some UIView features that are not exposed Calayer:

(Shadow, fillet, colored border, 3D transform, non-rectangular range, transparent matte, multilevel non-linear animation)


Second, matrix transformation

First, we look at the matrix structure in the plane transformation:

struct Cgaffinetransform
{
CGFloat A, B, C, D;
CGFloat tx, Ty;
};

In order to unify the change of the two-dimensional graph in a coordinate system, the concept of homogeneous coordinates is introduced, that is, a graph is represented by a three-dimensional matrix, where the third column is always (0,0,1) and used as the standard of coordinate system. So all the changes are done by the first two columns.
The above parameters are represented in the matrix as:
|a b 0|
|c D 0|
|tx Ty 1|

operation principle: the original coordinate is set to (x,y,1);
                            |a    b    0|
   [x,y,  1]        |c    d    0|     =     [AX + CY + tx   BX + DY + ty  1];
                            |TX    ty  1|

After the matrix operation coordinates [AX + CY + tx   BX + DY + ty  1], we compare the following: br> First type: set a=d=1, b=c=0 .  
[AX + CY + tx   BX + DY + ty  1] = [X  + tx  y + ty  1];
Visible, at this time, coordinates are translated according to the Vector (tx,ty), in fact this is the function
Cgaffinetransform cgaffinemaketranslation (cgfloat tx,cgfloat ty) calculation principle.
Second type: set b=c=tx=ty=0 .  
[ax + CY + tx   BX + DY + ty  1] = [ax    dy   1];
Visible, at this time, coordinates x is scaled according to a, Y is scaled by D, a,d is the scale factor of x, Y, which is actually the function
Cgaffinetransform Cgaffinetransformmakescale (cgfloat SX, CGFloat sy) Calculation principle. A corresponds to the sx,d corresponding to the SY.
The third type: set Tx=ty=0,a=cos?,b=sin?,c=-sin?,d=cos? .
[AX + CY + tx   BX + DY + ty  1] = [Xcos?-Ysin?    xsin? + Ycos?  1];
Visible, this time,? is the angle of rotation, counterclockwise is positive, clockwise is negative. This is, in fact, the computational principle of the function
Cgaffinetransform cgaffinetransformmakerotation (cgfloat angle). The radian of angle is.

The "affine" in cgaffinetransform means that regardless of the value of the transformation matrix, the parallel two lines in the layer remain parallel in the transformation, and in the real world, when the object is away from us, the cause of the view will look smaller, In theory, the edges farther away from our view are shorter than those near the perspective, but it doesn't actually happen, and our current view is equidistant, that is, in the 3D transformation, it remains parallel, similar to the affine transformation mentioned earlier. Catransform3d's perspective effect is controlled by a simple element in a matrix: M34. The default value of M34 is 0, we can apply the perspective effect by setting M34 to -1.0/D, and D represents the distance between the imaginary camera and the screen, in pixels, how should this distance be calculated? It doesn't really need to be, it's probably just a matter of estimating one (for the use of M34, I'll illustrate this in a later chapter ).


Third, visual effects

fillet : Calayer A property called Conrnerradius controls the curvature of the corner of the layer. It is a floating-point number that defaults to 0 (0 is right-angled), but you can set it to any value. By default, this curvature value affects only the background color without affecting the background picture or sublayer. However, if you set Maskstobounds to Yes, everything inside the layer will be intercepted.
Border : Calayer the other two very useful properties are borderwidth and bordercolor. Together, they define the drawing style for the edges of the layer. This line (also called a stroke) is drawn along the bounds of the layer and also contains the corners of the layer. BorderWidth is a floating-point number that defines the border thickness in points, with the default of 0.borderColor defining the color of the border, and the default is black. BorderColor is a cgcolorref type, not a uicolor, so it is not a built-in object for cocoa. However, you must also know that the layer refers to bordercolor, although the attribute declaration does not prove it. The behavior of Cgcolorref in quoting/releasing is very similar to that of NSObject. However, the OBJECTIVE-C syntax does not support this practice, so the Cgcolorref attribute can only be declared by the Assign keyword, even if it is a strong reference.
Shadow : The Shadowoffset property controls the direction and distance of the shadow. It is a cgsize value, the width controls the lateral displacement of the shadow, and the height controls the longitudinal displacement. The default value for Shadowoffset is {0,-3}, meaning that the shadow has an upward displacement of 3 points relative to the y-axis.


Iv. Dedicated Layers

Cashapelayer (You can set the fillet of several corners separately)
Cashapelayer is a layer subclass that is drawn by vector graphics instead of bitmap. You specify properties such as color and lineweight, use Cgpath to define the shapes you want to draw, and then cashapelayer automatically render them. Of course, you can also use the core graphics directly to the original Calyer content to draw a path, compared to straight down, using Cashapelayer has the following advantages:
Rendering is fast, Cashapelayer uses hardware acceleration, and drawing the same graph is much faster than using the core graphics.
Using memory efficiently, a cashapelayer doesn't need to create a hosted graphic like a normal calayer, so no matter how big it is, it won't take up too much memory.
is not clipped by the layer boundary, and a cashapelayer can be drawn outside the bounds. Your layer path will not be clipped like the normal calayer using the core graphics (as we saw in chapter II).
Does not appear pixelated, when you make a 3D transformation for cashapelayer, it does not become pixelated like a normal layer with a homestay map.


V. Type of animation

1. Implicit animations

It is called implicit because we do not specify any type of animation. We changed only one attribute, and then the core animation to decide how and when to animate. When you change a property, how does the Core animation determine the type and duration of the animation? The actual time that the animation executes depends on the settings of the current transaction, depending on the layer behavior. A transaction is actually a mechanism used by the core animation to contain a set of property animations, and any layer property that alters the animation with the specified transaction does not change immediately, but instead begins to transition to the new value with an animation as soon as the transaction is committed. Catransaction does not have attributes or instance methods, and it cannot be created with the +alloc and-init methods. However, you can use +begin and +commit to enter the stack or stack separately. Any layer properties that can be animated are added to the transaction at the top of the stack, and you can set the animation time for the current transaction by using the +setanimationduration: method, or the +animationduration method to get the value (default 0.25 seconds).
Core animation automatically starts a new transaction in each run loop cycle (the run loop is the thing that iOS collects user input, handles timers or network events, and redraws the screen), even if you don't explicitly use [catransaction begin] Start a transaction, and any changes to the properties in a run loop loop will be lumped together and then animated 0.25 seconds at a time.

We know that core animation usually animates all properties of Calayer (animated properties), but UIView closes this feature of the layer it is associated with. To better illustrate this, we need to know how implicit animations are implemented. Each uiview has a delegate to its associated layers, and provides a way to implement-actionforlayer:forkey. When not in the implementation of an animation block, UIView returns nil for all layer behavior, but within the animation block range, it returns a non-null value.


the property behavior of the Calayer is not normal, because changing the properties of a layer does not take effect immediately, but rather changes the update over a period of time. How did this happen?
When you change the properties of a layer, the value of the property is updated immediately (if you read its data, you will see that its value is in effect at the moment you set it up), but the screen does not change immediately. This is because the property you set does not directly adjust the appearance of the layer, but instead, he simply defines the appearance that will change after the layer animation ends.
When you set the Calayer property, you are actually the model that defines how the layer is displayed after the current transaction ends. Core animation plays the role of a controller and is responsible for constantly updating the state of the view's properties on the screen based on layer behavior and transaction settings.
Duration and RepeatCount are all 0 by default. But this does not mean that the animation is 0 seconds or 0 times, where 0 represents only "default", that is, 0.25 seconds and 1 times,

In iOS, the screen is redrawn 60 times per second. If the animation is longer than 60 per second, the Core animation needs to reorganize the layers on the screen between setting a new value and the new value to take effect. This means that Calayer must know the record of the property value currently displayed on the screen in addition to the "real" value (which is the value you set).

The display values for each layer property are stored in a separate layer called the rendering layer, which can be accessed through the-presentationlayer method. This rendering layer is actually a copy of the model layer, but its property values represent the current appearance at any given moment. In other words, you can get the values that are actually displayed on the current screen by rendering the layer's values.


In the first chapter, we mentioned that in addition to the layer tree, there is also a rendering tree. The rendering tree is formed by the rendering layer of all layers in the layer tree. Note that rendering a layer is created only when the layer is first committed (that is, the first time it is displayed on the screen), so calling-presentationlayer before that will return nil. You may notice that there is a method called –modellayer. Calling –modellayer on the rendering layer will return the Calayer on which it is rendering. Calling-modellayer on a layer usually returns –SELF (the original layer we've created is actually a data model).

How a moving layer is rendered through the data model

In most cases, you don't need direct access to the rendering layer, and you can interact with the model layer to let the core animation update the display. Rendering layers can be useful in both cases, one for synchronous animations and one for handling user interaction.

If you're implementing a timer-based animation (see Chapter 11th, "Timer-based animation"), rather than just transaction-based animations, it's useful to know exactly where a layer is displayed at a certain point in time.
If you want your animated layer to respond to user input, you can use the-hittest: Method (See chapter III, "Layer geometry") to determine whether a specified layer is touched, and then call-hittest on the rendering layer instead of the model layer: it will make more sense, Because the render layer represents the layer position that the user is currently seeing, not the position after the current animation ends.


2. Explicit animations
1. Property animations
First, let's Explore property animations. A property animation acts on a single property of a layer, specifying a target value for it, or a series of values that will be animated. Property animations are divided into two types: base and keyframe.

I) Basic Animation
Animation is actually a period of time in the change, the simplest form is to change from one value to another value, which is the main function of cabasicanimation. Cabasicanimation is a subclass of Capropertyanimation, and Capropertyanimation's parent class is caanimation,caanimation and core Animation the abstract base class for all animation types. As an abstract class, caanimation itself does not do much work, it provides a timing function (see Chapter Tenth "Buffering"), a delegate (for feedback animation state) and a removedoncompletion, Used to identify whether an animation is automatically released after the end (default yes, to prevent memory leaks). Caanimation also implements a number of protocols, including Caaction (allowing subclasses of caanimation to provide layer behavior).
Capropertyanimation by specifying the animation's KeyPath action on a single property, Caanimation is typically applied to a specified calayer, so this refers to the keypath of a layer. It is actually a critical path (some dot notation can point to any nested object in a hierarchical relationship), not just the name of an attribute, because it means that the animation can be used not only for the properties of the layer itself, but also for the properties of its child members, even some virtual properties.
Cabasicanimation inherits from Capropertyanimation and adds the following properties:
ID Fromvalue
ID Tovalue
ID byvalue

II) Keyframe Animation
Cabasicanimation reveals the mechanisms behind most implicit animations, which is really interesting, but explicitly adding cabasicanimation to a layer can only say thankless compared to implicitly animations.
Cakeyframeanimation is another class of uikit that is not exposed but powerful. Like Cabasicanimation, Cakeyframeanimation is also a subclass of Capropertyanimation, which still works on a single attribute, but unlike Cabasicanimation, It is not limited to setting a starting and ending value, but it can be animated according to a series of random values.

2. Animation Group
Cabasicanimation and cakeyframeanimation only work on individual properties, and Caanimationgroup can group them together. Caanimationgroup is another subclass that inherits from Caanimation, and it adds a property of a animations array that can be used to assemble other animations. We combine the underlying animations of the Keyframe animation and the adjustment layer background color in Listing 8.6.

3. Transition
Transitions do not animate between two values as smoothly as property animations, but affect the entire layer's changes. Transition animations first show the appearance of the previous layer and then transition to a new look through a swap. To create a transition animation, we will use Catransition, which is also a subclass of another caanimation, unlike other subclasses, Catransition has a type and subtype to identify the transform effect.
To cancel an animation during animation, you can use the key parameter in the-addanimation:forkey: method to retrieve an animation after adding an animation, using the following method:-(Caanimation *) Animationforkey: (NSString *) Key However, it is not supported to modify animations while the animation is running, so this method is primarily used to detect the properties of an animation, or to determine whether it is added to the current layer. To terminate a specified animation, you can remove it from the layer using the following method:
-(void) Removeanimationforkey: (NSString *) key;
Or remove all animations:
-(void) removeallanimations;
Once the animation has been removed, the appearance of the layer is immediately updated to the value of the current model layer. In general, the animation is automatically removed after the end, unless you set removedoncompletion to No, and if you set the animation to not be automatically removed after the end, you need to remove it manually when it is not needed, otherwise it will persist in memory until the layer is destroyed.


Six, buffer

Camediatimingfunction

So how do you use the buffer equation? You first need to set the Timingfunction property of the Caanimation, which is an object of the Camediatimingfunction class. If you want to change the timing function of an implicit animation, you can also use Catransaction's +setanimationtimingfunction: method.
Here are some ways to create camediatimingfunction, the simplest way is to call +timingfunctionwithname: the constructor method. Here are some of the constants that are passed in:

Kcamediatimingfunctionlinear
Kcamediatimingfunctioneasein
Kcamediatimingfunctioneaseout
Kcamediatimingfunctioneaseineaseout
Kcamediatimingfunctiondefault



Seven, timer

When you set a nstimer, he will be inserted into the current task list and will not be executed until the specified time has elapsed. But when the timer is started there is no time limit, and it is only executed after the last task in the list has been completed. This usually results in a delay of several milliseconds, but it can cause a long delay if the previous task takes a long time to complete.
With Cadisplaylink instead of Nstimer, the frame rate is guaranteed to be continuous enough to make the animation look smoother, but even cadisplaylink does not guarantee that every frame is executed as planned, Some discrete tasks or events that are out of control, such as a resource-intensive daemon, can cause animations to drop frames occasionally. When using Nstimer, the timer will open once the opportunity is available, but the cadisplaylink is not the same: if it loses the frame, it will ignore them directly and then run the next update.

When you run an animation, the process is broken by four separate stages:
Layout-This is the stage for preparing your view/layer hierarchy, and for setting layer properties (position, background color, border, and so on).
Show-This is the stage where the layer's hosted picture is drawn. Drawing may involve your-drawrect: and-drawlayer:incontext: The call path of the method.
Prepare-This is the stage in which core animation prepares to send the animated data to the rendering service. This is also the point at which core animation will perform some other transaction such as decoding the picture that will be displayed during the animation.
Commit-This is the final stage where Core animation packages all layers and animated properties and then sends it to the rendering service via IPC (internal processing communication) for display.
The GPU is optimized for a specific task: it collects pictures and shapes (triangles), runs transformations, applies textures and mixes, and then transports them to the screen. Broadly speaking, most calayer properties are plotted using GPUs.


Eight, Bezier curve

Bézier curve ( Bezier curve ) is a mathematical curve applied to a two-dimensional graphical application. curve Definition: Start point, end point (also called Anchor Point), control point. By adjusting the control point, the shape of the Bezier curve changes. 1962 , French mathematician Pierre Bézier The first to study the method of the vector drawing curve, and gives the detailed calculation formula, so the curve drawn by this formula is named by his surname, called Bezier curve.

In the following formula:B (t) is the coordinate of the point at t time;

P0 is the starting point , Pn is the end point , Pi is the control point

First-order Bezier curves ( line segments ):

Meaning: A line segment described by a continuous point from P0 to P1


Quadratic Bezier curve ( parabola ):

Principle: A continuous point Q0 from P0 to P1, describing a line segment.
A continuous point Q1 from P1 to P2 that describes a line segment.
A continuous point B (t) from Q0 to Q1 that describes a two-time Bezier curve.

Experience: P1-p0 is the tangent of the curve at P0.

Sanche Besel Curve:

General formula:


Gauche Besel Curve:

4-Step curve:


5-Step curve:

Summary: This section provides an overview of the concepts related to core animation, and in the next section, I will illustrate the use of animations.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Core Animation Advanced Theoretical Knowledge Summary

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.