Brief analysis on the principle and implementation of iOS animation--core Animation

Source: Internet
Author: User

This article reprinted to Http://www.tuicool.com/articles/e2qaYjA original https://tech.imdada.cn/2016/06/21/ios-core-animation/themeCore AnimationBackground

With the expansion of the business, more and more people began to use the Tatsu-Da client, to participate in the crowdsourcing logistics industry. The Dada client is divided into iOS platform and Android platform.

App development is also moving from a fast iterative, coarse-grained development to a high-reusability, to improve the refinement of user withdrawals. iOS animations interact well and use a wide range of user experiences without the need for smooth interface transformations. To this end, the Dassault iOS team has explored the implementation of the animation and the rationale behind it.

Objective
    • Understanding the core Animation Basic framework
    • Understanding the definition of a layer
    • Process for parsing animations
    • Mastering the principles of 3D animation
    • Implementing code implementations for 3D animations
Basic framework

The Core animation is located below the AppKit, Uikit, and is integrated into the Cocoa, Cocoa touch of the view. Of course, core animation provides a lot of interfaces to view so that developers have better control over animations.

Definition of a layer
    1. Developer All about core animation is based on a layer, and the Layer object is a 2D plane that is projected vertically in 3D space backwards.
    2. A layer captures the content provided by the view and caches the content in a bitmap.
    3. The operation of bitmaps at the hardware level is much faster than at the software level.
Understand
    1. Vertical projection can be imagined as an object standing in front of a wall, a light source perpendicular to the wall, illuminating the object, the shadow left on the wall, because it is a vertical light source, whether the object is away from the wall, or close to the wall, the size of the shadow will not change.

    2. Each view control in an iOS program has its own child controls on the Layer,view, such as Label,image, which is what the view provides to the layer, and the parameters such as panning, rotating, zooming, and so on, are state information.

    3. Layer-based animations, the Core animation the bitmap and state information retained by the layer to the graphics hardware, and the graphics hardware is responsible for using the new information manipulation bitmap. Based on view drawing, it is by calling the view's DrawRect method to redraw the content with the new parameters to change the view. This painting is expensive because drawing on the bus path consumes the CPU to complete the work.

Process of animation

The principle of animation

The following content will be involved in the knowledge, in turn, the mathematical coordinate system, the linear algebra matrix, the physical imaging principle, the mathematical similarity triangle, the mathematical equations group. Don't worry, we'll start with the basics and make understanding more efficient.

Coordinates

In the layer plane coordinate system, two coordinate systems are used.

    • Point-based coordinate system
The origin is in the upper-left corner of the layer, right is the positive direction of the x-axis, downward is the positive direction of the y-axis, and the X-and y-coordinates of a point are in points.
    • Unit coordinate system
The origin is in the upper-left corner of the layer, right is the positive direction of the x-axis, downward is the positive direction of the y-axis, and the X-and y-coordinates of a point are the values of the relative x-axis, y-axis, and the value range [0,1]. The anchor point (anchorpoint) uses the unit coordinate system, as shown in position depending on the anchor point.

The role of anchor points

The anchor point determines the position of the z-axis when the animation changes. For example, because the anchor points are different, the layer rotates around the z axis as well.

Matrix
    1. The layer bitmap is panned, rotated, scaled, and transformed by a matrix.
    2. Matrix multiplication is only meaningful if the number of columns (column) of the first matrix is the same as the number of rows (row) of the second matrix.
    3. The bitmap of the layer is made up of points, each point can correspond to the 1x4 matrix, multiplied by a 4x4 transformation matrix, to get a 1x4 matrix, which is the result of the transformation.

Matrix multiplication

    1. The number of rows in Matrix C equals the number of rows in matrix A, and the number of columns in C equals the number of columns in B.
    2. The element of the nth column of the product C is equal to the sum of the elements of the line m of the matrix A and the corresponding elements of the nth column of Matrix B.
Thinking?
1. Why the point coordinates are converted to 1x4 Matrix 2. Why the transformation matrix must be a 4x4 matrix 3. How to achieve move, zoom, rotate
Homogeneous matrices
    1. Homogeneous coordinates are represented by a vector of n+1 dimensions, which is originally n-dimensional vectors.
    2. Using the 1x4 matrix, the coordinates of the three-dimensional coordinates of the relative point are homogeneous.
Homogeneous coordinate transformation (y, Z)--(xxh,  yxh,  zxh,  H)--(Yˊ, Zˊ, h) Homogeneous coordinate restoration (yˊ, Zˊ, h) (1) (y, z)      
What if I don't use the 1x4 homogeneous matrix and the 4x4 transformation matrix?

Use only the 3x3 transformation matrix:

              M11, M12, m13{x, y, z} * {M21, M22, M23} = {x ', y ', z '}              M31, M32, M33

Xˊ=XXM11 + yxm21 + zxm31 can only achieve scaling on individual axes in the case of a predetermined variable factor (M11, M21, M31)

But after using the 1x4 homogeneous matrix and the 4x4 transformation matrix

xˊ= Xxm11 + yxm21 + zxm31 + 1xm41m11=2 m21=0 m31=0 m41=8  can simultaneously zoom in the positive direction of the x-axis by twice times and translate 8 units in the positive direction of the X-axis
The purpose of introducing homogeneous coordinates is to combine multiplication and addition in matrix operations. Basic Transformation matrix
    • Matrix is to use the value of the special position in the matrix, when doing matrix multiplication, to achieve the point coordinate transformation, the following often with the transformation matrix

3D animation effects

The 3D of Calayer in iOS is not really 3D, but just 3D on a two-dimensional plane, and the projection plane is the plane of the phone screen, which is the XY axis.

In this way, only the basic transformation matrix to achieve the translation, scaling, rotation, there will not be nearly large and small perspective effect.

So how can it be so much smaller?
    • To achieve near-large and small-size purposes, it is necessary to do a viewpoint transformation of the layer before the system can do vertical projection. Such a vertical projection is a near-large, far-smaller object observed by the viewpoint.

    • The position of the z axis of the layer is specified by Anchorpoint, and the so-called Anchorpoint (anchor Point) is the point that remains constant in the transformation, that is, the origin of a layer in the transformation, and the XYZ three axes intersect at this point. Common locations for anchor points

    • In the origin (0, 0) along the positive direction of the Y axis, get the coordinate system, first select a viewpoint in the z axis

    • Add two child layers, and the viewing area will see two short lines at the top of the child layer, green in front, red in the back, and equal in length

    • The projection of a relative x-axis is obtained by the viewpoint of the top.

    • The Green Line and red line are equal in length, and the perspective effect of "near large and far small" is caused by the projection of the viewpoint.

So as long as the iOS vertical projection, the layer as a viewpoint projection transformation, you can get perspective effect practice perspective
    • The coordinate system used, the red point for the observation area point, the red dot to do a viewpoint projection, to get green points, while the red dots do Z axis vertical line to get black dots.

    • Using the similar triangle principle, the following formula is obtained

    • After simplifying the formula, the value of the 方程1 x-axis of the green point is only related to the z-axis value of the viewpoint

    • Align the coordinates of H = 1 on the red dot (6, 0, 5, 1) and get the homogeneous matrix of the transformed green points by multiplying a matrix

    • The transformed matrix is only related to the value of the viewpoint Z axis, so only the M34 is set, and the Restore of (6, 0, 5, 1 + 5r) is obtained方程2

    • Combined 方程1 and 方程2 , finally get

At this point, as long as the value of the transformation matrix M34 is the value of the viewpoint Z axis, we can get the code realization of the corresponding Viewpoint projection transformation matrix animation.
    • Use the Delta startup page to practice the above. PS: In order to see the introduction, the method is not encapsulated

  • Property declaration

    Dada LogoUILabel *namelab;  Dada UILabel *deslab;  Reliable delivery, at your side    
  • Initialize the settings, set the opacity to two labels to 0, and shrink to 0.5 times times the original

    -(void) viewdidload{   [Super Viewdidload];    0.f;   Self.nameLab.layer.transform = Catransform3dmakescale (1.f);   0.f; self.desLab.layer.transform = Catransform3dmakescale (1.f);}    
    • Animation settings, separate logo and label implementation animations

      -(void)viewdidappear:(BOOL) animated{   [selfanimationdadalabel];   [SelfAnimationdadalogo];}    
  • Animation of label, using UIView's own block mode

    - (void) animationdadalabel{[UIView animatewithduration:0.5f animations:^{Enlarge and blur Self.nameLab.alpha =0.5f; Self.nameLab.layer.transform = Catransform3dmakescale (1.2f, 1.2f, 1.f); Self.desLab.alpha = 0.5f; self.desLab.layer.transform = Catransform3dmakescale ( 1.2f, 1.2f, 1.f);} completion:^ (BOOL finished) {[UIView animatewithduration:0.5f animations:^{//Restore and clear Self.nameLab.alpha = 1.F; self.nameLab.layer.transform = Catransform3dmakescale (1.f, 1.f, 1.f); self.desLab.alpha = 1.F; Self.desLab.layer.transform = Catransform3dmakescale (1.f, 1.f, 1.f); }]; }];} 
  • Animation of the logo, using the Cabasicanimation object

    - (void) animationdadalogo{Catransform3d transform = catransform3didentity; TRANSFORM.M34 =-1/100.0f;Set the viewpoint on the z-Axis square z=100At the end of the animation, the z-axis is in negative direction of catransform3d Starttransform = catransform3dtranslate (transform,0,0,-60);At the end of the animation, rotate counterclockwise around the y axis by 90 degrees Catransform3d firsttransform = Catransform3drotate (Starttransform, M_pi_2,0,1,0);//by cabasicanimation Modify Transform properties cabasicanimation *animation1 = [cabasicanimation Animationwithkeypath:@ "transform"]; //move backwards and rotate counterclockwise around the y-axis 90 degrees Animation1.fromvalue = [Nsvalue valuewithcatransform3d: Catransform3didentity]; Animation1.tovalue = [Nsvalue valuewithcatransform3d:firsttransform]; //although there is only one animation, but with group only for good later expansion caanimationgroup *animationgroup = [Caanimationgroup animation]; Animationgroup.animations = [Nsarray arraywithobjects:animation1, Nil]; Animationgroup.duration = 0.5f; animationgroup.//Animation callback, at the end of the animation call animationdidstop animationgroup.removedoncompletion = NO; //stop at the end of the animation, do not revert to //apply animations to logoimg layers [Self.logoImg.layer addanimation: Animationgroup forkey:@ "Fristanimation"];}         
  • In fact, only the logo using "Half animation", logo side to move backwards, while counterclockwise around the z axis rotation of 90 degrees, after the end of the animation, through the callback to complete the rest of the "half animation." With these two parts, the implementation, backward movement at the same time counterclockwise rotation, rotation to 90 degrees, moving forward, while continuing to rotate 90 degrees counterclockwise

    - (void) Animationdidstop: (Caanimation *) Anim finished: (BOOL) flag{if (flag) {if (Anim = = [Self.logoImg.layer animationforkey:@ "Fristanimation"]) {Catransform3d transform = catransform3didentity; TRANSFORM.M34 =-1/100.0f;Set the viewpoint on the z-Axis square z=100At the beginning of the animation, the z-axis negative direction is catransform3d Starttransform = catransform3dtranslate (transform,0, 0,-60); //When the animation starts, rotate clockwise 90 degrees around the y-axis catransform3d secondtransform = Catransform3drotate (Starttransform,-m_pi_2, 0, 1, 0); //Modify Transform property by cabasicanimation cabasicanimation *animation = [cabasicanimation animationwithkeypath:@ " Transform "]; //move forward and rotate counterclockwise around the y-axis 90 degrees Animation.fromvalue = [Nsvalue valuewithcatransform3d:secondtransform]; animation.tovalue = [ Nsvalue Valuewithcatransform3d:catransform3didentity]; Animation.duration = 0.5f; //Apply animations to logoimg layers [Self.logoImg.layer addanimation:animation forkey:@ "Secondanimation"];  }} 
  • Final effect (PS: for explanation only)

Summary

Based on the above, summarize the following core animation related focus

    • Understanding layer meaning, layer is the core and carrier of animation
    • To understand the purpose of two planar coordinate systems, when doing 3D viewpoint transformation, we should help to think through three-dimensional coordinate system.
    • Understanding matrices, the purpose of using homogeneous coordinates
    • If you do not understand the imaging principle, you can search for relevant information
    • Further practice through code

Disclaimer: The image of this article originates from Apple Coreanimation Programming Guide, if you want to learn more about Apple's official documentation

Brief analysis on the principle and implementation of iOS animation--core Animation

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.