Basic Android tutorial -- attribute animation of Android animation collection-see

Source: Internet
Author: User
Tags getcolor

Basic Android tutorial -- attribute animation of Android animation collection-see
1. Evaluator custom1) Evaluator Introduction

The ValueAnimator in the previous section is simple and practical. The first step of using an animation is as follows:
Call ValueAnimatorOfInt(),OfFloat() OrOfObject() Create a ValueAnimator instance using static methods!
In this example, ofInt and ofFloat are used to animation floating point and integer data respectively!
SoOfObject()? Initial object and end object? How to transition? Or how to use it?
Well, with questions, let's first understand one thing: Evaluator. In fact, we have mentioned this thing in the definition of attribute Animation:

Used to tell the animation system how to transition from the initial value to the end value! Okay, let's get started!
Let's go to the source code of IntEvaluator and see what is written in it?

Yes.TypeEvaluatorInterface, and then rewriteEvaluate ()Method. The parameters are as follows:

Fraction: Animation completion level. Based on this, we can calculate the animation value. StartValue: Animation start value EndValue: Animation end value

Animation value = initial value + completion degree * (end value-Initial Value)

There are also FloatEvaluator. We want to tell the system how to overdo the object from the initial object to the end object, then we need
Implement it by yourselfTypeEvaluatorThe interface, that is, the custom Evaluator, is useless. Let's write an example to see it:

2) Example

Run:

Code Implementation:

Define an objectPoint. javaThe object contains only the x and y attributes and the get and set methods ~

/** * Created by Jay on 2015/11/18 0018. */public class Point {    private float x;    private float y;    public Point() {    }    public Point(float x, float y) {        this.x = x;        this.y = y;    }    public float getX() {        return x;    }    public float getY() {        return y;    }    public void setX(float x) {        this.x = x;    }    public void setY(float y) {        this.y = y;    }}

Then customize the Evaluator class:PointEvaluator. javaTo override the evaluate method ~

/** * Created by Jay on 2015/11/18 0018. */public class PointEvaluator implements TypeEvaluator
  
   {    @Override    public Point evaluate(float fraction, Point startValue, Point endValue) {        float x = startValue.getX() + fraction * (endValue.getX() - startValue.getX());        float y = startValue.getY() + fraction * (endValue.getY() - startValue.getY());        Point point = new Point(x, y);        return point;    }}
  

Then customize a View class:AnimView. java, Very simple ~

/** * Created by Jay on 2015/11/18 0018. */public class AnimView extends View {    public static final float RADIUS = 80.0f;    private Point currentPoint;    private Paint mPaint;    public AnimView(Context context) {        this(context, null);    }    public AnimView(Context context, AttributeSet attrs) {        super(context, attrs);        init();    }    public AnimView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    private void init() {        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);        mPaint.setColor(Color.BLUE);    }    private void drawCircle(Canvas canvas){        float x = currentPoint.getX();        float y = currentPoint.getY();        canvas.drawCircle(x, y, RADIUS, mPaint);    }    private void startAnimation() {        Point startPoint = new Point(RADIUS, RADIUS);        Point endPoint = new Point(getWidth() - RADIUS, getHeight() - RADIUS);        ValueAnimator anim = ValueAnimator.ofObject(new PointEvaluator(), startPoint, endPoint);        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {            @Override            public void onAnimationUpdate(ValueAnimator animation) {                currentPoint = (Point) animation.getAnimatedValue();                invalidate();            }        });        anim.setDuration(3000l);        anim.start();    }    @Override    protected void onDraw(Canvas canvas) {        if (currentPoint == null) {            currentPoint = new Point(RADIUS, RADIUS);            drawCircle(canvas);            startAnimation();        } else {            drawCircle(canvas);        }    }}

LastMainActivity. javaYou can instantiate this View ~

public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(new AnimView(this));    }}
3) Sample enhanced Edition

We add the color changes when the circle moves on the basis of the above example ~
Here we use another ObjectAnimator to load the color change animation. We add multiple
Int color to control the color. In addition, write the getColor () and setColor () methods. Let's first define an Evaluator ~

Run:

Implementation Code:

ColorEvaluator. java:

/** * Created by Jay on 2015/11/18 0018. */public class ColorEvaluator implements TypeEvaluator
  
   {    @Override    public Integer evaluate(float fraction, Integer startValue, Integer endValue) {        int alpha = (int) (Color.alpha(startValue) + fraction *                (Color.alpha(endValue) - Color.alpha(startValue)));        int red = (int) (Color.red(startValue) + fraction *                (Color.red(endValue) - Color.red(startValue)));        int green = (int) (Color.green(startValue) + fraction *                (Color.green(endValue) - Color.green(startValue)));        int blue = (int) (Color.blue(startValue) + fraction *                (Color.blue(endValue) - Color.blue(startValue)));        return Color.argb(alpha, red, green, blue);    }}
  

Then add the color, get, and set methods to the custom View. Create an ObjectAnimator,
And the AnimatorSet, and then combine the animation. Here we just need to add something, for fear that readers may have problems,
Create another View ~

AnimView2.java:

/*** Created by Jay on 0018. */public class AnimView2 extends View {public static final float RADIUS = 80366f; private Point currentPoint; private Paint mPaint; private int mColor; public AnimView2 (Context context) {this (context, null);} public AnimView2 (Context context, AttributeSet attrs) {super (context, attrs); init ();} public AnimView2 (Context context, AttributeSet attrs, int de FStyleAttr) {super (context, attrs, defStyleAttr);} private void init () {mPaint = new Paint (Paint. ANTI_ALIAS_FLAG); mPaint. setColor (Color. BLUE);} private void drawCircle (Canvas canvas) {float x = currentPoint. getX (); float y = currentPoint. getY (); canvas. drawCircle (x, y, RADIUS, mPaint);} private void startAnimation () {Point startPoint = new Point (RADIUS, RADIUS); Point endPoint = new Point (g EtWidth ()-RADIUS, getHeight ()-RADIUS); ValueAnimator anim = ValueAnimator. ofObject (new PointEvaluator (), startPoint, endPoint); anim. addUpdateListener (new ValueAnimator. animatorUpdateListener () {@ Override public void onAnimationUpdate (ValueAnimator animation) {currentPoint = (Point) animation. getAnimatedValue (); invalidate () ;}}); ObjectAnimator objectAnimator = ObjectAnimator. ofObject (this, Color, new ColorEvaluator (), Color. BLUE, Color. RED); // The animation set adds the first two Animations together. with simultaneously plays the AnimatorSet animatorSet = new AnimatorSet (); animatorSet. play (anim ). with (objectAnimator); animatorSet. setStartDelay (1000l); animatorSet. setDuration (3000l); animatorSet. start () ;}@ Override protected void onDraw (Canvas canvas) {if (currentPoint = null) {currentPoint = new Point (RADIUS, RADIUS); drawCircle (canvas ); StartAnimation () ;}else {drawCircle (canvas) ;}// get and set methods of color ~ Public int getColor () {return mColor;} public void setColor (int color) {mColor = color; mPaint. setColor (color); invalidate ();}}

Then, set MainActivity and setContentView to change AnimView to AnimView2 ~

2. Interpolator)

Well, we talked about this stuff when talking about the animation of the supplementary room ~ Do you still have an impression?

In addition, the animation and property animation are both available.TimeInterpolatorInterface
This interface is used to be compatible with the previous Interpolator, so that all the previous Interpolator implementation classes can be taken directly.
Used in property animation! We can call the setInterpolator () method of the animation object to set different Interpolator!
First, let's let the ball drop from the top of the center of the screen to the bottom ~
Then we will call the following statement for our set Animation:
AnimatorSet. setInterpolator (new AccelerateInterpolator (2f ));
The value in the brackets is used to control the acceleration ~

Running Effect:

It seems a bit out of common sense. It should be normal. Let's replace itBounceInterpolatorTry ~

Hey, the results are awesome. Of course there are N more systems that provide good Interpolator. You can try them one by one.
Don't get stuck with everyone ~

Let's take a look:

1) internal implementation mechanism of Interpolator

We first go to the source code of the TimeInterpolator interface and find that there is only oneGetInterpolation() Method;

Simple Explanation:
The getInterpolation () method receives an input parameter. The value of this parameter changes with the running of the animation,
However, its variation is quite regular, that is, it increases at a constant speed according to the preset animation length, and the variation range is 0 to 1.
That is to say, when the animation starts, the input value is 0, and when the animation ends, the input value is 1, while the intermediate value is
It changes with the animation running duration between 0 and 1.
HereInputThe value determinesTypeEvaluatorInterfaceFraction.
The input value is passed into the getInterpolation () method after calculation by the system, and then we can implement it ourselves.
GetInterpolation() The algorithm in the method calculates a return value based on the input value, and the return value is fraction.

Let's take a look.LinearInterpolatorCode in:

No input value is directly returned, that is, the value of fraction is equal to the value of input, which is uniformly moving.
Implementation of Interpolator! In fact, it is nothing more than algorithms. This involves some mathematical things.
I realized the importance of mathematics. I will post another article here.BounceInterpolatorSource code:

Don't ask me about the algorithms here. I don't know either. Let's find another easy-to-understand algorithm:AccelerateDecelerateInterpolator

This Interpolator accelerates and then slows down:
(Float) (Math. cos (input + 1) * Math. PI)/2.0f) + 0.5fAlgorithm understanding:
Solution: The value range of input is [0, 1]. The value range of cos is [π, 2 π], and the corresponding values are-1 and 1;
After dividing by 2 and adding 0.5, the value range returned by the getInterpolation () method is [0, 1].
The corresponding graph is as follows:

So it is a process of acceleration first and then deceleration!

Well, it's hard to learn about scum ..., All of the above are moved in Uncle Guo's article... I want to quietly...

2) custom Interpolator

>
Well, I 'd better wait for a moment. Write a custom Interpolator example first:
Very simple. Implement the TimeInterpolator interface and override the getInterpolation method.

The sample code is as follows:

    private class DecelerateAccelerateInterpolator implements TimeInterpolator {        @Override        public float getInterpolation(float input) {            if (input < 0.5) {                return (float) (Math.sin(input * Math.PI) / 2);            } else {                return 1 - (float) (Math.sin(input * Math.PI) / 2);            }        }    }

Call setInterpolator (new DecelerateAccelerateInterpolator () to set it ~
Due to space limitations, no longer need to map ~

3. ViewPropertyAnimator

After 3.1, a new feature is added to the system to provide a more convenient usage for View animation operations!
If a TextView is changed from normal to transparent in the past, it is written as follows:

ObjectAnimator animator = ObjectAnimator.ofFloat(textview, alpha, 0f);  animator.start(); 

Using ViewPropertyAnimator to achieve the same effect is easier to understand:

textview.animate().alpha(0f);  

Also supportedConcatenation, Combining multiple animations, setting the duration, and setting the Interpolator ~

textview.animate().x(500).y(500).setDuration(5000)          .setInterpolator(new BounceInterpolator());  

The usage is very simple. You can check the document when using it ~, In addition, pay attention to the following details!

The entire ViewPropertyAnimator function is built on the newly added animate () method of the View class,
This method will create and return a ViewPropertyAnimator instance, and then call all the methods,
All properties set are completed through this instance. Use ViewPropertyAnimator After the animation definition is complete, The animation will Auto Start.
And this mechanism is equally effective for composite animations, as long as we constantly attach new methods,
The animation will not be executed immediately. After all the methods set on ViewPropertyAnimator are executed,
The animation is automatically started. Of course, if you do not want to use this default mechanism, you can also explicitly call
Start() Method to start the animation. All interfaces of ViewPropertyAnimator are designed using the concatenation syntax. The returned values of each method are
It InstanceTherefore, after calling a method, you can directly concatenate and call another method, so that all
Functions are concatenated. We can even use only one line of code to complete the animation function of any complexity.
 

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.