Android animation analysis and android Analysis

Source: Internet
Author: User

Android animation analysis and android Analysis
Preface

In application development, animation is an essential part. Otherwise, many visual effects may appear abrupt. Today, let's take a look at the animation library in Android.


Animation Process in View

The alpha animation of the View is directly implemented by modifying the transparency through the setAlpha (float al) function. scaling, translation, and rotation are all implemented through the graphic matrix transformation. Graph transformation is the basic knowledge in graphics. Simply put, each transformation is a matrix operation. In Android, the Canvas class contains the current matrix. Currently, Canvas is called. when drawBitmap (bm, x, y, Paint) is drawn, android performs a matrix operation on bmp, and then displays the operation result on the Canvas. In this way, programmers only need to constantly modify the Canvas matrix and refresh the screen, and the objects in the View will not stop performing graphic transformations, and the animation will be formed.

View: sets the animation attributes. When the animation is started, the invalidate method is called to re-paint the View. This triggers the onDraw function. In the onDraw function, call the getTransformation method of the animation to obtain the matrix of the current time point. The getTransformation function calls the applyTransformation function of the animation, the applyTransformation function calculates the value of the View attribute at the current time using a calculated factor (calculated by the percentage calculated by the interpolation tool through the animation execution) and modifies the View attribute to achieve graphical transformation. View determines the return value of getTransformation. If it is true, the animation is not completed. Call the invalidate method to refresh the screen and re-paint the View to enter the next frame of the animation. If it is false, the animation is completed.


The Android platform provides two types of animations: Tween (complementary animation) and Frame (Frame. The Tween animation is used to continuously transform the images (such as translation, scaling, and rotation) of objects in the scenario to produce the animation effect. The Frame Animation is used to play the pre-prepared images of each Frame in sequence, similar to a quick slide. The Tween animation pre-defines an animation, which specifies the type (rotation, translation, scaling, etc.), start time, duration, and start value of the graphic transformation, when the View is drawn, these attribute values are modified along the timeline to achieve the animation effect. Animations can be defined by code or xml. If the animation is defined in xml, use AnimationUtils. loadAnimation (context, R. anim. your_anim); to load it. Alpha: Transparency Animation: This animation modifies the transparency of a View within a specified period of time. An example of a transparency animation from 0.3 to 1.0f is as follows: Code defines an animation:
  AlphaAnimation alphaAnimation = new AlphaAnimation(0.3f, 1.0f) ;        alphaAnimation.setDuration(1000);
Xml definition Animation:
<? Xml version = "1.0" encoding = "UTF-8"?> <! -- Transparency --> <alpha xmlns: android = "http://schemas.android.com/apk/res/android" android: fromAlpha = "1" android: toAlpha = "0" android: duration = "1000"/>
Then, run setAnimation or startAnimation of the view to set the animation.
Scale: the scaling animation for the view. You must specify the zooming values on the x and Y axes. In this example, the View is scaled to half the original size within one second, and the center of the Zoom is the center of the view. Code definition Animation:
        ScaleAnimation scaleAnimation = new ScaleAnimation(1.0f, 0.5f, 1.0f, 0.5f,0.5f, 0.5f);        scaleAnimation.setDuration(1000);
Xml definition Animation:
<? Xml version = "1.0" encoding = "UTF-8"?> <! -- Scale --> <scale xmlns: android = "http://schemas.android.com/apk/res/android" android: fromXScale = "1" android: fromYScale = "1" android: toXScale = "0.5" android: toYScale = "0.5" android: Short Tx = "0.5" android: Short ty = "0.5" android: duration = "3000"/>

Translate: A displacement animation is an animation that moves a View from a point to a point. For example, you can move a view from the (0, 0) position to the (100,100) position within one second. Code definition:
        TranslateAnimation translateAnimation = new TranslateAnimation(0, 100, 0, 100) ;        translateAnimation.setDuration(1000);

XML definition Animation:
<? Xml version = "1.0" encoding = "UTF-8"?> <! -- Mobile --> <translate xmlns: android = "http://schemas.android.com/apk/res/android" android: fromXDelta = "0" android: fromYDelta = "0" android: toXDelta = "100" android: toYDelta = "100" android: duration = "000"/>
Rotate: the rotation animation is responsible for adjusting the view angle, for example, rotating the view 360 degrees from the current angle. Code definition:
  RotateAnimation rotateAnimation = new RotateAnimation(0, 360) ;        rotateAnimation.setDuration(1000);
XML definition:
<? Xml version = "1.0" encoding = "UTF-8"?> <! -- Rotate --> <rotate xmlns: android = "http://schemas.android.com/apk/res/android" android: fromDegrees = "0" android: toDegrees = "360" android: Export Tx = "50%" android: required ty = "50%" android: duration = "1000"/>


Frame Animation

Frame Animation can be imagined as a very short movie. It consists of a limited number of key frames. When this frame is animated, these key frames are quickly switched to achieve the animation effect.

<?xml version="1.0" encoding="utf-8"?><animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false">    <item android:drawable="@drawable/p1" android:duration="200" />    <item android:drawable="@drawable/p2" android:duration="200" />    <item android:drawable="@drawable/p3" android:duration="200" />    <item android:drawable="@drawable/p4" android:duration="200" />    <item android:drawable="@drawable/p5" android:duration="200" />    <item android:drawable="@drawable/p6" android:duration="200" />    <item android:drawable="@drawable/p7" android:duration="800" />    <item android:drawable="@drawable/p8" android:duration="200" />    <item android:drawable="@drawable/p9" android:duration="200" />    <item android:drawable="@drawable/p10" android:duration="200" />    <item android:drawable="@drawable/p11" android:duration="200" /></animation-list>
The frame animation is not the same as the compensation animation, for example:

// Obtain the AnimationDrawable sample animation drawable frameAnim = (AnimationDrawable) getResources () through the resource file of the frame-by-frame animation (). getDrawable (R. drawable. my_frame_anim); // set AnimationDrawable to the background of myView. setBackgroundDrawable (frameAnim );

Animation interpolation device (Interpolator)

In the compensation animation, we generally only define the first and last frames, and then the system automatically generates intermediate frames. The process of generating intermediate frames can be "interpolation ". The interpolation tool is used to tell the animation how an attribute (such as a color gradient) changes over time and the attribute values corresponding to each time point in the duration period. The following are some common interpolation tools:


By default, the android system supports nine kinds of interpolation devices, including ingress, AccelerateInterpolator, ingress, BounceInterpolator, CycleInterpolator, timer, LinearInterpolator, and OverShootInterpolator, you can customize the interpolation tool ).

For example, if an alpha animation changes from 0.0f to 1.0f within one second, the linear interpolation animation is executed at a constant speed. However, the animation of the interpolation tool will become faster and faster as time increases.

The interpolation tool uses the getInterpolation method to obtain the interpolation factor. The calculation of the interpolation factor is also completed in this function. For example, the linear interpolation tool uses a uniform animation. Therefore, in its getInterpolation function, the interpolation factor is only related to time and has nothing to do with other factors. The parameter in the getInterpolation (int inpput) function is the animation execution percentage. It can also be considered as the animation execution time and animation cycle percentage. The value ranges from 0.0f to 1.0f, that is, the animation starts to end.

/** * An interpolator where the rate of change is constant * */public class LinearInterpolator implements Interpolator {    public LinearInterpolator() {    }        public LinearInterpolator(Context context, AttributeSet attrs) {    }        public float getInterpolation(float input) {        return input;    }}
Let's look at the accelerator interpolation, that is, the animation speed will get faster and faster over time. Let's take a look at its getInterpolation implementation:

    public float getInterpolation(float input) {        if (mFactor == 1.0f) {            return input * input;        } else {            return (float)Math.pow(input, mDoubleFactor);        }    }
By default, mFactor is 1.0f. As the animation is executed, the input increases slowly, and the value range returned by the getInterpolation function increases, leading to faster animation.

Use Matrix to customize animations

During Custom Animation, we mainly override the applyTransformation (float interpolatedTime, Transformation t) method, which is called to implement animation operations during animation execution, here we need to modify the alpha, zoom, pan, and other animations. InterpolatedTime is a factor calculated by the interpolation tool. It is calculated by the animation execution percentage and the interpolation tool's policy. The value ranges from 0.0f to 1.0f. Parameter t is the encapsulation class of matrix transformation. Here we will only discuss custom animations implemented using matrices. For example, we need to customize an animation that can implement the Y axis rotation animation in a system earlier than API 11. In android, The RorateAnimation animation only supports the rotation animation on the Z axis, this can be achieved through matrices. For more information about the Matrix, see the principles, code verification, and application of image transformation Matrix in Android. (1) Explanation of Android Matrix theory and application, and Android-Matrix image transformation processing.


/*** @ Author mrsimple */public class RotateYAnimation extends Animation {private int halfWidth; private int halfHeight; // use Camera to implement 3D Rotation of Camera mCamera = new Camera (); // protected float mRotateY = 0.0f;/*** width. height indicates the width and height of the view for which the animation is executed. The following two parameters are the width and height of the parent of the view that executes the animation */@ Override public void initialize (int width, int height, int parentWidth, int parentHeight) {super. initialize (width, height, parentWidth, parentHeight); setDuration (2000); setFillAfter (true); halfWidth = width/2; halfHeight = height/2; setInterpolator (new LinearInterpolator ();} // set the Rotation Angle public void setRotateY (float rorateY) {mRotateY = rorateY;} @ Override protected void applyTransformation) {final Matrix = t. getMatrix (); mCamera. save (); // use Camera to set the rotation angle. rotateY (mRotateY * interpolatedTime); // apply the Rotation Transformation to the matrix. getMatrix (matrix); mCamera. restore (); // before transformation, move the animation center point from the default (0, 0) (0,-halfHeight) matrix. preTranslate (0,-halfHeight); // After the transform, move halfWidth and halfHeight from (-halfWidth,-halfHeight) to bring it back to (0, 0) matrix. postTranslate (0, halfHeight); // View view ;}}

Code:

Button btn = new Button (MainActivity. this); btn. setText ("RotateY"); MyAnimation animation = new MyAnimation (); animation. setRotateY (45f); animation. setDuration (2000); // start the animation btn. startAnimation (animation );
Effect (the view in is not a button, but the view in my other example ):




How to Set hidden animation in android View

MAppHiddenAction. setDuration (400 );
MAppGridView. startAnimation (mHiddenAction );
ScrollView. startAnimation (mAppHiddenAction );
Relativelayout. startAnimation (mAppHiddenAction );

The subsequent code should be executed after mAppHiddenAction is completed, instead of directly executing it here. You can use the hander + timer to run the code later.
ScrollView. setVisibility (View. GONE );
MAppGridView. setVisibility (View. GONE );
TV. setVisibility (View. GONE );
Btn_save.setVisibility (View. GONE );

Android animation effect

Set fillAfter = true in xml

Related Article

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.