Android animation player growth notes

Source: Internet
Author: User
Tags gety

Android animation player growth notes

Before introducing the implementation of animation effects in this article, we will first introduce several knowledge points related to property animation.

ValueAnimator and ObjectAnimator. Interpolator interpolation and TypeEvaluator estimator.

Before Android, the system provides two animation effects: frame-by-frame animation and tweened animation. Frame Animation is similar to playing a movie. It splits the entire video into one piece and plays it in a coherent manner. You can perform operations such as Zoom, pan, and rotate the view. After 3.0, a new animation mode was created, called property animation.

Causes of property Animation

Attribute animation is not used to replace the animation, but to solve the events that cannot be completed by the animation. If our requirements exceed the operation scope for controlling view rotation, scaling, and translation, We need to select attribute animation. So what can an attribute animation do? The following are some of the points. Of course, attribute animation is very powerful and not limited to the points I listed.

Attribute animation can be used to animation a non-view class. Property animation can truly change the attribute values of a view object. The compensation animation only changes the animation effect of the view.

ValueAnimator and ObjectAnimator

ObjectAnimator is the most important execution class in property animation. ObjectAnimator can operate on the attribute value of an object. However, this attribute value must have the get and set methods, and you can also set the view execution line, control by interpolation.
A simple example:

ObjectAnimator.ofFloat(view, "rotationY", 0.0F, 360.0F).setDuration(500).start();

Its operation attributes include x/y, scaleX/scaleY, rotationX/rotationY, transitionX/transitionY, and so on.
The preceding example shows how to modify a single attribute value of a view. You can also modify multiple attributes at the same time.

PropertyValuesHolder property value holder

PropertyValuesHolder pvhLeft = PropertyValuesHolder.ofInt("left", 0, 1);PropertyValuesHolder pvhTop = PropertyValuesHolder.ofInt("top", 0, 1);ObjectAnimator.ofPropertyValuesHolder( this, pvhLeft, pvhTop).

Provides a non-existent property value.

ObjectAnimator anim = ObjectAnimator.ofFloat(view, "long", 1.0F, 0.0F).setDuration(500);anim.start();anim.UpdateListener(new AnimatorUpdateListener() {    @Override    public void onAnimationUpdate(ValueAnimator animation) {        float cVal = (Float) animation.getAnimatedValue();        view.setAlpha(cVal);        view.setScaleX(cVal);        view.setScaleY(cVal);    }});

The above mentioned changes the attribute values of the existing setter and getter methods of the object. If the object does not provide the setter and getter methods for a property, we can also modify these attribute values. The following two implementation methods are provided:

Implementation through valueAnimation, which will be explained below.

Write a package class by yourself. The setter and getter methods are provided for this attribute.

class ViewWrapper{    private View mView;    public int getWidth(){        return mView.getLayoutParams().width;    }}

ValueAnimator includes all the core functions of the Property Animation, such as the Animation time, start and end attribute values, and the calculation method of the corresponding time attribute values.
There are two steps to apply an attribute Animation:
1. Calculate the attribute value. 2. Execute the corresponding action based on the property value.
ValueAnimator only completes the first step. To complete the second step, you must use the ValueAnimator. onUpdateListener interface. In this method, you can use the getAnimatedValue () function of the ValueAnimator object to obtain the current attribute value.

ValueAnimator animation = ValueAnimator. ofFloat (0f, 1f); animation. setDuration (1000); animation. addUpdateListener (new AnimatorUpdateListener () {@ Override public void onAnimationUpdate (ValueAnimator animation) {Log. I ("update", (Float) animation. getAnimatedValue ()). toString (); // you can change the attribute of the view based on the property value obtained by getAnimatedValue to execute some actions.}); animation. setInterpolator (new CycleInterpolator (3); animation. start ();

Time Interpolator interpolation and TypeEvaluator Estimator

Time interplator: defines the way the attribute value changes, such as linear Uniform change, start to slow and then gradually increase. In Property Animation, It is TimeInterplator and in View Animation is Interplator. The two are the same. Before 3.0, only Interplator is used. After 3.0, code is transferred to TimeInterplator. Interplator inherits from TimeInterplator and has no other internal code.

AccelerateInterpolator acceleration, slow intermediate acceleration DecelerateInterpolator deceleration at the beginning, fast at the beginning, then slow down AccelerateDecelerateInterolator acceleration and then slow at the end, intermediate acceleration AnticipateInterpolator reverse, first, change to the opposite direction and then accelerate the playback of AnticipateOvershootInterpolator. First, change to the opposite direction, and then accelerate the playback. The playback will go beyond the target value and then slowly move to the BounceInterpolator jump, when the target value is reached, the value jumps. For example, if the target value is 100, the following values may be 90,100, 77, CycleIinterpolator loops in sequence. The animation loops a certain number of times, and the value is changed to a sine function: Math. sin (2 * mCycles * Math. PI * input) LinearInterpolator linear, linear and even change OvershottInterpolator rebound, and then slowly change to the destination value TimeInterpolator an interface that allows you to customize interpolator.

TypeEvaluator: Calculate the attribute value of the current time based on the start, end, And TimeInterpolation of the attribute. android provides the following evalutor:

IntEvaluator: the attribute value type is int. FloatEvaluator: the attribute value type is float. ArgbEvaluator: the property value type is a hexadecimal color value. TypeEvaluator: an interface that can be used to customize the Evaluator.

Of course, you can also define the estimator as follows:

public class FloatEvaluator implements TypeEvaluator {     public Object evaluate(float fraction, Object startValue, Object endValue) {            float startFloat = ((Number) startValue).floatValue();            return startFloat + fraction * (((Number) endValue).floatValue() - startFloat);     }}

Instance
Next we will implement the following:

In the implementation of this example, we also focus on the animation technology in this example by integrating the above knowledge content in ValueAnimator and ObjectAnimator. Code attached: <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjxwcmUgY2xhc3M9 "brush: java;"> Package com. example. custom. animation; import java. util. arrayList; import com. example. custom. r; import android. animation. animator; import android. animation. animatorListenerAdapter; import android. animation. animatorSet; import android. animation. argbEvaluator; import android. animation. objectAnimator; import android. animation. valueAnimator; import android. app. activity; import android. content. context; import android. graphics. canvas; import android. graphics. paint; import android. graphics. radialGradient; import android. graphics. shader; import android. graphics. drawable. shapeDrawable; import android. graphics. drawable. shapes. ovalShape; import android. OS. bundle; import android. view. motionEvent; import android. view. view; import android. view. animation. accelerateInterpolator; import android. view. animation. decelerateInterpolator; import android. widget. linearLayout; public class bouncingbils extends Activity {@ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. bouncing_bils); LinearLayout container = (LinearLayout) findViewById (R. id. container); container. addView (new MyAnimationView (this);} public class MyAnimationView extends View {private static final int RED = 0xffFF8080; private static final int BLUE = 0xff80ff; public final ArrayList Bils = new ArrayList (); AnimatorSet animation = null; public MyAnimationView (Context context) {super (context); ValueAnimator colorAnim = ObjectAnimator. ofInt (this, "backgroundColor", RED, BLUE); colorAnim. setDuration (3000); colorAnim. setEvaluator (new ArgbEvaluator (); colorAnim. setRepeatCount (ValueAnimator. INFINITE); colorAnim. setRepeatMode (ValueAnimator. REVERSE); colorAnim. start () ;}@ Override public boolean onTouch Event (MotionEvent event) {if (event. getAction ()! = MotionEvent. ACTION_DOWN & event. getAction ()! = MotionEvent. ACTION_MOVE) {return false;} // initialize a jump ball ShapeHolder newBall = initBouncingBall (event. getX (), event. getY (); float startY = newBall. getY (); float endY = getHeight ()-50; float h = (float) getHeight (); float eventY = event. getY (); int duration = (int) (500 * (h-eventY)/h); // operate the value of the Y attribute of newBall ValueAnimator bounceAnim = ObjectAnimator. ofFloat (newBall, "y", startY, endY); bounceAnim. setDuration (duration); bounceAnim. setInterpolator (new AccelerateInterpolator (); ValueAnimator squashAnim1 = ObjectAnimator. ofFloat (newBall, "x", newBall. getX (), newBall. getX ()-25f); squashAnim1.setDuration (duration/4); squashAnim1.setRepeatCount (1); squashAnim1.setRepeatMode (ValueAnimator. REVERSE); squashAnim1.setInterpolator (new DecelerateInterpolator (); ValueAnimator squashAnim2 = ObjectAnimator. ofFloat (newBall, "width", newBall. getWidth (), newBall. getWidth () + 50); squashAnim2.setDuration (duration/4); squashAnim2.setRepeatCount (1); squashAnim2.setRepeatMode (ValueAnimator. REVERSE); squashAnim2.setInterpolator (new DecelerateInterpolator (); ValueAnimator stretchAnim1 = ObjectAnimator. ofFloat (newBall, "y", endY, endY + 25f); stretchAnim1.setDuration (duration/4); Round (1); Round (new DecelerateInterpolator (); Round (ValueAnimator. REVERSE); ValueAnimator stretchAnim2 = ObjectAnimator. ofFloat (newBall, "height", newBall. getHeight (), newBall. getHeight ()-25); stretchAnim2.setDuration (duration/4); stretchAnim2.setRepeatCount (1); stretchAnim2.setInterpolator (new DecelerateInterpolator (); iterator (ValueAnimator. REVERSE); ValueAnimator bounceBackAnim = ObjectAnimator. ofFloat (newBall, "y", endY, startY); bounceBackAnim. setDuration (duration); bounceBackAnim. setInterpolator (new DecelerateInterpolator (); AnimatorSet bouncer = new AnimatorSet (); bouncer. play (bounceAnim ). before (squashAnim1); bouncer. play (squashAnim1 ). with (squashAnim2); bouncer. play (squashAnim1 ). with (stretchAnim1); bouncer. play (squashAnim1 ). with (stretchAnim2); bouncer. play (bounceBackAnim ). after (stretchAnim2); ValueAnimator fadeAnim = ObjectAnimator. ofFloat (newBall, "alpha", 1f, 0f); fadeAnim. setDuration (1, 250); fadeAnim. addListener (new AnimatorListenerAdapter () {@ Override public void onAnimationEnd (Animator animation) {bcalls. remove (ObjectAnimator) animation ). getTarget () ;}}); AnimatorSet animatorSet = new AnimatorSet (); animatorSet. play (bouncer ). before (fadeAnim); animatorSet. start (); return true;} private ShapeHolder initBouncingBall (float x, float y) {int red = (int) (Math. random () * 255); int green = (int) (Math. random () * 255); int blue = (int) (Math. random () * 255); int color = 0xff000000 | red <16 | green <8 | blue; int darkColor = 0xff000000 | red/4 <16 | green/4 <8 | blue/4; // instantiate a circular OvalShape circle = new OvalShape (); circle. resize (50f, 50f); // set the Paint brush shape ShapeDrawable drawable = new ShapeDrawable (circle); paint Paint = drawable. getPaint (); // The first parameter. The second parameter indicates the Center Coordinate, radius, center color, and edge color of the gradient circle. The Renderer tiled mode is RadialGradient gradient = new RadialGradient (37.5f, 12.5f, 50f, color, darkColor, Shader. tileMode. CLAMP); // set the paint color set for the paint brush. setShader (gradient); ShapeHolder shapeHolder = new ShapeHolder (drawable); shapeHolder. setX (x-25f); shapeHolder. setY (y-25f); shapeHolder. setPaint (paint); bils. add (shapeHolder); return shapeHolder;} @ Override protected void onDraw (Canvas canvas) {for (int I = 0; I <bils. size (); ++ I) {ShapeHolder shapeHolder = bils. get (I); canvas. save (); canvas. translate (shapeHolder. getX (), shapeHolder. getY (); shapeHolder. getShape (). draw (canvas); canvas. restore ();}}}}

package com.example.custom.animation;import android.graphics.Paint;import android.graphics.RadialGradient;import android.graphics.drawable.ShapeDrawable;import android.graphics.drawable.shapes.Shape;import android.view.View;public class ShapeHolder {    private float x = 0, y = 0;    private int color;    private float alpha = 1f;    private Paint paint;    private ShapeDrawable shape;    private RadialGradient gradient;    public void setPaint(Paint value) {        paint = value;    }    public Paint getPaint() {        return paint;    }    public void setX(float value) {        x = value;    }    public float getX() {        return x;    }    public void setY(float value) {        y = value;    }    public float getY() {        return y;    }    public void setShape(ShapeDrawable value) {        shape = value;    }    public ShapeDrawable getShape() {        return shape;    }    public int getColor() {        return color;    }    public void setColor(int value) {        shape.getPaint().setColor(value);        color = value;    }    public void setGradient(RadialGradient value) {        gradient = value;    }    public RadialGradient getGradient() {        return gradient;    }    public void setAlpha(float alpha) {        this.alpha = alpha;        shape.setAlpha((int)((alpha * 255f) + .5f));    }    public float getWidth() {        return shape.getShape().getWidth();    }    public void setWidth(float width) {        Shape s = shape.getShape();        s.resize(width, s.getHeight());    }    public float getHeight() {        return shape.getShape().getHeight();    }    public void setHeight(float height) {        Shape s = shape.getShape();        s.resize(s.getWidth(), height);    }    public ShapeHolder(ShapeDrawable s) {        shape = s;    }}

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.