Android full set of animation skills

1. Android View animation framework

    The Animation framework defines several common animations of transparency, rotation, scaling and displacement, and controls the entire View. The implementation principle is that each time the view is drawn, the drawChild function in the ViewGroup where the View is located obtains the Transformation value of the View's Animation, and then calls canvas. concat(transformToApply.getMatrix()), complete the animation frame by matrix operation. If it is not completed, continue to call the invalidate() function, start the next drawing to drive the animation, and complete the drawing of the entire animation.
    View animation is easy to use and has rich effects. It provides four animation methods: AlphaAnimation, RotateAnimation, TranslateAnimation, and ScaleAnimation, and provides animation collection AnimationSet, which can mix and use various animations. Before Android 3.0, view animation dominated, but with the introduction of the property animation framework after Android 3.0, its scenery is not as good as before. Compared with attribute animation, a very big defect of view animation is that it does not have interactivity. When an element has view animation, the position of its response event is still in the place before the animation, so view animation can only do ordinary animation. effect to avoid interaction. But its advantages are also very obvious, that is, the efficiency is relatively high and the use is convenient.

    View animation is very simple to use. Not only can an animation process be described by an XML file, but also code can be used to control the entire animation process.

(1), transparency animation

   A transition animation that adds transparency to the view.

AlphaAnimation aa = new AlphaAnimation(0, 1);
aa.setDuration (1000);
view.startAnimation (aa);

(2), rotation animation

Adds a rotating transform animation to the view.

RotateAnimation ra = new RotateAnimation(0, 360, 100, 100);
ra.setDuration(1000);
view.startAnimation (ra);

    The parameters are the starting angle of the rotation and the coordinates of the center point of the rotation. Of course, the reference system of the rotation animation can be controlled by setting parameters. Here, the reference system of the rotation animation is set as the center.

RotateAnimation ra1 = new RotateAnimation(0, 360, RotateAnimation.RELATIVE_TO_SELF, 0.5F, RotateAnimation.RELATIVE_TO_SELF, 0.5F);

(3), displacement animation

Added displacement animation for view movement.

TranslateAnimation ta = new TranslateAnimation(0, 200, 0, 300);
ta.setDuration(1000);
view.startAnimation (ta);

(4), zoom animation

Animate the zoom of the view

ScaleAnimation sa = new ScaleAnimation (0, 2, 0, 2);
sa.setDuration (1000);
view.startAnimation (in);

    Like the rotation animation, the zoom animation can also set the center point of Luo Fang, and set the center as its own center effect.

ScaleAnimation sa1 = new ScaleAnimation(0, 1, 0, 1, Animation.RELATIVE_TO_SELF, 0.5F, Animation.RELATIVE_TO_SELF, 0.5F);
sa1.setDuration(1000);
view.startAnimation (sa1);

(5), animation collection

    With AnimationSet, animations can be displayed in a combined form:

AnimationSet as = new AnimationSet(true);
as.setDuration(1000);

AlphaAnimation aa = new AlphaAnimation(0, 1);
aa.setDuration (1000);
as.addAnimation (aa);


RotateAnimation ra = new RotateAnimation(0, 360, 100, 100);
ra.setDuration(1000);
as.addAnimation(ra);



TranslateAnimation ta = new TranslateAnimation(0, 200, 0, 300);
ta.setDuration(1000);
as.addAnimation(ta);

ScaleAnimation sa = new ScaleAnimation (0, 2, 0, 2);
sa.setDuration (1000);
as.addAnimation (in);

view.startAnimation(as);

    You can directly copy and run the code to see the effect!

    For animation events, Android also provides corresponding listener callbacks, the code:

as.setAnimationListener (new Animation.AnimationListener ()
    @Override
    public void onAnimationStart(Animation animation) {
        // start the animation
    }

    @Override
    public void onAnimationEnd(Animation animation) {
        // end of animation
    }

    @Override
    public void onAnimationRepeat(Animation animation) {
        // animation repeats
    }
});

2. Property animation

    Due to the limitations of the existing animation framework Animation before Android 3.0 - the animation only changes the display and cannot respond to events. Therefore, after Android 3.0, Google proposed a new animation framework such as attribute animation to achieve richer effects.

    The most used in the Animator framework is the combination of AnimatorSet and ObjectAnimator, using ObjectAnimator for finer control, only controlling one attribute value of an object, and using multiple ObjectAnimators to combine into AnimatorSet to form an animation. And ObjectAnimator can be driven automatically, you can call setFrameDelay(long frameDelay) to set the gap time between animation frames. The most important thing is that property animation truly controls the property value of a View by calling the get and set methods of the property. Therefore, the powerful property animation framework can basically achieve all animation effects.

(1)、ObjectAnimator

    ObjectAnimator is the most important implementation class in the property animation framework. Creating an ObjectAnimator only needs to return an ObjectAnimator object directly through its static factory class. The parameters include an object and the property name of the object, but this property must also have get and set functions, and the set function will be called internally to modify the object property value through the Java reflection mechanism. Similarly, you can also call setInterpolator to set the corresponding interpolator.

    Next, imagine adding a translation animation to a Button. After using the previous animation frame to translate, the click event will not be triggered. The effective area of ​​the click is still the original place, and there will be no click event in the place where the click is moved. The property animation is different. It actually changes the properties of a View, so the area of ​​the event response also changes. At this time, when the moved button is clicked, it will respond to the click event.

    The property animation translation code is as follows:

ObjectAnimator animator = ObjectAnimator.ofFloat(
        imageView,
        "translationX",
        200F);
animator.setDuration (300);
animator.start();

    When using ObjectAnimator, it is very important that the properties to be manipulated must have get and set methods, otherwise ObjectAnimator will not take effect. The following properties are commonly used:

  • translationX and translationY: These two properties control the position of the View object from the coordinates of the upper left corner of its layout container as an increment.
  • rotation, rotationX and rotationY: These three properties control the 2D and 3D rotation of the View object around the pivot.
  • scaleX and scaleY: These two properties control the 2D scaling of the View object around its pivot.
  • pivotX and pivotY: These two properties control the pivot position of the View object, and rotate and scale around this pivot. By default, the pivot position is the center of the View object.
  • x and y: These two simple and practical properties describe the final position of the View object in its container, which is the cumulative sum of the initial upper-left corner coordinates and the translationX and translationY values.
  • alpha: Indicates the alpha transparency of the View object. The default value is 1 (opaque), and 0 is fully transparent (invisible).

    According to the above, the animation effects achieved by the view animation are basically included here.

    So if a property has no get and set methods, is the property animation helpless? The answer is no, Google provides two solutions at the application layer to solve this problem, one is to indirectly add get and set methods to this property by customizing a property class or wrapper class; or to implement it through ValueAnimator, ValueAnimator In the following content, let's first look at the method of using the wrapper class to add get and set methods to an attribute. The code is as follows:

private static class WrapperView {
    private View mTarget;

    public WrapperView(View mTarget) {
        this.mTarget = mTarget;
    }

    public int getWidth() {
        return mTarget.getLayoutParams().width;
    }

    public void setWidth(int width) {
        mTarget.getLayoutParams().width = width;
        mTarget.requestLayout();
    }
}

    Through the above code, it wraps a layer with a property, and provides it with get and set methods. When using, you only need to manipulate the wrapper class to indirectly call the get and set methods. The code is as follows:

WrapperView wrapperView = new WrapperView(view);
ObjectAnimator.ofInt(wrapperView, "width", 500).setDuration(5000).start();

(2)、PropertyValuesHolder

    Similar to AnimationSet in view animation, in property animation, if multiple animations are to be applied to multiple properties of the same object at the same time, PropertyValuesHolder can be used to achieve this. For example, for translation animation, if the zoom of the X and Y axes is changed at the same time during the translation process, it can be implemented like this, the code:

PropertyValuesHolder pvh1 = PropertyValuesHolder.ofFloat("translationX", 300);
PropertyValuesHolder pvh2 = PropertyValuesHolder.ofFloat("scaleX", 1f, 0, 1f);
PropertyValuesHolder pvh3 = PropertyValuesHolder.ofFloat("scaleY", 1f, 0, 1f);
ObjectAnimator.ofPropertyValuesHolder(pvh1, pvh2, pvh3).setDuration(1000).start();

    In the code, the PropertyValuesHolder object is used to control the three properties of translationX, scaleX, and scaleY. The most important thing is to call the ObjectAnimator.ofPropertyValuesHolder method to achieve the joint effect of multi-property animation. The entire implementation method is very similar to the use of AnimatorSet.

(3)、ValueAnimator   

    ValueAnimator occupies a very important position in property animation. Although it is not as dazzling as ObjectAnimator, it is the core of property animation. ObjectAnimator also inherits from ValueAnimator.

public final class ObjectAnimator extends ValueAnimator

    ValueAnimator itself does not provide any animation effects. It is more like a value generator, which is used to generate numbers with certain rules, so that the caller can control the implementation process of animation. The general usage of ValueAnimator: usually monitor the value in the AnimatorUpdateListener of ValueAnimator The transformation completes the animation transformation.

    

ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 100);
valueAnimator.setTarget(imageView);
valueAnimator.setDuration(1000).start();
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        Float value = (Float) animation.getAnimatedValue();
    }
});

(4) Monitoring of animation events

    A complete animation has four processes: Start, Repeat, End, and Cancel. It provides an interface through Android to easily monitor these four events:

ObjectAnimator anim = ObjectAnimator.ofFloat(imageView, "alpha", 0.5F);
anim.addListener(new Animator.AnimatorListener() {
    @Override
    public void onAnimationStart(Animator animation) {
        
    }

    @Override
    public void onAnimationEnd(Animator animation) {

    }

    @Override
    public void onAnimationCancel(Animator animation) {

    }

    @Override
    public void onAnimationRepeat(Animator animation) {

    }
});
anim.start();

    Most of the time, we only care about the onAnimationEnd event, so Android also provides an AnimatorListenerAdapter to let us choose the necessary events to listen to:

    

anim.addListener(new AnimatorListenerAdapter() {
    @Override
    public void onAnimationEnd(Animator animation) {
        super.onAnimationEnd (animation);
    }
});

(5)、AnimatorSet

    For a property to act on multiple property animation effects at the same time, the PropertyValuesHolder has been used to achieve such an effect. The AnimatorSet can not only achieve this effect, but also achieve more precise sequence control. The same is to achieve the animation effect demonstrated above using PropertyValuesHolder, if you use AnimatorSet to achieve, then the code is as follows:

ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(imageView, "translationX", 300f);
ObjectAnimator objectAnimator1 = ObjectAnimator.ofFloat(imageView, "scaleX", 1f, 0f, 1f);
ObjectAnimator objectAnimator2 = ObjectAnimator.ofFloat(imageView, "scaleY", 1f, 0f, 1f);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.setDuration(1000);
animatorSet.playTogether(objectAnimator, objectAnimator1, objectAnimator2);
animatorSet.start();

    In property animation, AnimatorSet controls the cooperative working mode of multiple animations through playTogether(), playSquentially(), animSet.play().width(), before(), after(), so as to be correct Precise control of animation playback order.

(6), use attribute animation in XML

    Property animation, like view animation, can also be written directly in XML files, the code:

<?xml version="1.0" encoding="utf-8"?>
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="1000"
    android:propertyName="scaleX"
    android:valueFrom="1.0"
    android:valueTo="2.0"
    android:valueType="floatType">

</objectAnimator>

    The premise is to use XML to define the attribute animation XML file must be placed under the res/animator/filename.xml folder to be recognized, otherwise it will not be recognized. It is found that property animation and view animation are written very similar in XML files. Use in the program:

Animator anim = AnimatorInflater.loadAnimator(this,R.animator.filename);
anim.setTarget(view);
anim.start();

(7), View's animate method

    After Android 3.0, Google added the animate method to View to directly drive attribute animation. The code is as follows:

imageView.animate()
        .alpha(0)
        .y(300)
        .setDuration(300)
        .withStartAction(new Runnable() {
            @Override
            public void run() {

            }
        })
        .withEndAction(new Runnable() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        
                    }
                });
            }
        }).start();

3. Android layout animation

    Layout animation refers to the action on the ViewGroup, adding an animation transition effect when adding View to the ViewGroup. The simplest layout animation is in the XML of the ViewGroup, using the following code to turn on the layout animation:

android:animateLayoutChanges="true"

    With the above settings, when the ViewGroup is added to the View, the child View will show a gradually displayed transition effect, but this effect is the default displayed transition effect of Android, which cannot be replaced by a custom animation.

    You can also customize the transition effect of a child View by using the LayoutAnimatorController class and add a view animation, so that the child View has a zooming animation effect when it appears. Code:

LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
ScaleAnimation sa = new ScaleAnimation (0, 1, 0, 1);
sa.setDuration (2000);
//Set the display of the layout animation
LayoutAnimationController lac = new LayoutAnimationController(sa, 0.5f);
//set layout animation
ll.setLayoutAnimation (lac);

    The first parameter of LayoutAnimationController is the animation that needs to be applied, and the second parameter is the delay time displayed by each child View. When the delay time is not 0, the order in which the child Views are displayed can be set.

//order
public static final int ORDER_NORMAL  = 0;

//random
public static final int ORDER_REVERSE = 1;

//Reverse Order
public static final int ORDER_RANDOM  = 2;

Fourth, Interpolators - interpolator

    The interpolator is a very important concept of animation. Through the interpolator Interpolators, the animation transformation rate can be defined, which is very similar to the acceleration in physics. The main function is to control the change value of the target variable to make corresponding changes.

  • AccelerateDecelerateInterpolator is slower at the beginning and introduction of the animation, and accelerates in the middle
  • AccelerateInterpolator slows down at the beginning of the animation, then starts to speed up
  • AnticipateInterpolator starts backwards then forwards
  • AnticipateOvershootInterpolator starts backward and then throws a certain value forward and returns to the final value
  • BounceInterpolator bounces when the animation ends
  • CycleInterpolator animation loops a specific number of times, the rate changes along a sinusoidal curve
  • DecelerateInterpolator is fast and slow where the animation starts
  • LinearInterpolator changes at a constant rate
  • OvershootInterpolator throws forward a certain value and then returns to the original position
  • PathInterpolator Path Interpolator

5. Custom animation

    To create a custom animation, you only need to implement the logic of its applyTransformation, but usually, you also need to override the initalize method of the parent class to implement initialization. The applyTransformation method is as follows:

protected void applyTransformation(
        float interpolatedTime,
        Transformation t) {
}

    The first parameter, interpolatedTime, is the time factor of the interpolator mentioned above. This factor is calculated by the current completion percentage of the animation and the plug-in corresponding to the current time. The value ranges from 0 to 1.0.

    The second parameter, Transformation, is the encapsulation class of the matrix. Generally, this class is used to obtain the current position idea, as follows:

final Matrix matrix = t.getMatrix();

    By changing the obtained matrix object, the animation effect can be realized, and for the transformation operation of the matrix, basically any effect animation can be realized. For an introduction to matrix, you can view: In-depth understanding of Matrix in Android

@Override
protected void applyTransformation(
        float interpolatedTime,
        Transformation t) {
    final Matrix matrix = t.getMatrix();
    // Realize animation through various operations of matrix
}

    See how simple matrix changes can be animated by simulating the effect of a TV being turned off. The effect of turning off the TV is to continuously reduce the vertical scale of a picture. The corresponding matrix motion processing method is as follows:

@Override
protected void applyTransformation(
        float interpolatedTime,
        Transformation t) {
    final Matrix matrix = t.getMatrix();
    matrix.preScale(1,
            1 - interpolatedTime,
            mCenterWidth,
            mCenterHeight);
}

    Among them, mCenterWidth and mCenterHeight are the center point of the zoom, which can be set as the center of the image. In this way, a simple matrix transformation can simulate the animation of the TV turning off.

    It is also possible to set up a more precise interpolator and split the time factor from 0 to 1 into different processes, so that different processes can be animated differently. code show as below:

@Override
public void initialize(int width,
                       int height,
                       int parentWidth,
                       int parentHeight) {

    super.initialize(width, height, parentWidth, parentHeight);
    // set default duration
    setDuration(2000);
    // Retain state after animation ends
    setFillAfter(true);
    // set default interpolator
    setInterpolator(new BounceInterpolator());
    mCenterWidth = width / 2;
    mCenterHeight = height / 2;
}

    The core of custom animation - how to define the process of animation, code:

@Override
protected void applyTransformation(
        float interpolatedTime,
        Transformation t) {
    final Matrix matrix = t.getMatrix();
    mCamera.save();
    // Use Camera to set the angle of rotation
    mCamera.rotateY(mRotateY * interpolatedTime);
    // apply the rotation transformation to the matrix
    mCamera.getMatrix(matrix);
    mCamera.restore();
    // Change the center of rotation by setting the offset before the matrix acts by the pre method
    matrix.preTranslate(mCenterWidth, mCenterHeight);
    matrix.postTranslate(-mCenterWidth, -mCenterHeight);
}

    Using the Camera class to achieve the animation effect through the above code is to set the rotation angle of the three coordinate axes, and the default rotation center can be changed through the last two lines of code.

Not finished, to be continued. . .

 

6. Open source code base

Finally, I will share a code base that I have accumulated for a long time, only you can't think of it, there is nothing you can't use, welcome to star

https://github.com/xijiufu

Since the github server is in the United States, access is sometimes very slow, and an open-source Chinese address library is also provided, and the codes of the two warehouses are updated synchronously:

http://git.oschina.net/xijiufu

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325469845&siteId=291194637