1. Frame by frame animation

Frame Animation, also called a Drawable Animation. Just as the name suggests, it is to play the picture frame by frame. The visual retention effect is used to set the drawable and duration of each frame, and the playing effect of Miyazaki hayao’s animation can be displayed.

Frame-by-frame animation can be set in code in two ways:

1. XML mode:

<animation-list xmlns:android="http://schemas.android.com/apk/res/android" 
    android:oneshot="false">
    <item
        android:drawable="@drawable/comp1_00000"
        android:duration="25"></item>
    <item
        android:drawable="@drawable/comp1_00001"
        android:duration="25"></item>
    <item
        android:drawable="@drawable/comp1_00002"
        android:duration="25"></item>
    <item
        android:drawable="@drawable/comp1_00003"
        android:duration="25"></item>
    <item
        android:drawable="@drawable/comp1_00004"
        android:duration="25"></item>
</animation-list>
Copy the code

Android :oneshot=”true”, which means the animation is played only once, and false which means the animation is played in a loop. Oneshot means oneshot in a movie.

2. Code mode:

AnimationDrawable animationDrawable = new AnimationDrawable(); for (int i=0; i< 5; i++) { int id = getResources().getIdentifier("comp1_0000" + i , "drawable", getPackageName()); Drawable drawable = ResourcesCompat.getDrawable(this.getResources(), id, null); animationDrawable.addFrame(drawable, 50); } animationDrawable.setOneShot(true); imageView.setBackground(animationDrawable);Copy the code

Note that both of the above methods only define the animation. The code for playing or stopping the animation is as follows:

AnimationDrawable drawable = (AnimationDrawable) imageView.getBackground(); //AnimationDrawable Drawable = //(AnimationDrawable) ResourcesCompat.getDrawable(this.getResources() // , R.drawable.frame_anim, null); drawable.start(); drawable.stop();Copy the code

2. Tween animation

Define the beginning and end keyframes of an animation, the two keyframes that the animation goes from (from) somewhere to (to) somewhere, and let Android compute each frame of the process. So we also specify how long the duration of the process lasts, and how the speed of the continuous process is Interpolator.

As we know, the essence of computer graphics transformation is matrix operation. The transparency transformation (AlphaAnimation) changes the pixel color A in ARGB, and the scaling transformation (ScaleAnimation) changes the graph coordinate position. Transparency in Android is a two-digit hexadecimal scalar, but position is a vector with direction and size, so the scale transformation also specifies the pivot point. If you do not specify the pivot point, Android will default to the center of the View (calculated in width and height) as the pivot point.

Translational transform (TranslateAnimation) only need to specify the start (fromXValue/fromXDelta, fromYValue/fromYDelta) and end position (toXValue/toXDelta, toYValue/toYDelta). A rotation animation specifies the Angle at which the rotation begins (fromDegrees) and the Angle at which the rotation ends (toDegrees). On pivotX,pivotY, the default axis is (0,0), which is the upper left corner of the screen.

When using TranslateAnimation or RotateAnimation, the displacement/Angle of translation or rotation can also be set in the form of proportion. Depending on the Size of your View or the Size of the parent View, you can set the displacement distance/Angle to how many times this Size.

ImageView imageView = this.findViewById(R.id.imageView); //TranslateAnimation TranslateAnimation = new TranslateAnimation(0, 400,0,800); // Set the Size of the View in the X-axis, TranslateAnimation TranslateAnimation = New TranslateAnimation(animation.relative_to_self, 0, Animation.relative_to_self, 1, animation.relative_to_parent,0, animation.relative_to_parent, 0.5f); //How long this animation should last translateAnimation.setDuration(2000); //true if the animation should apply its transformation after it ends translateAnimation.setFillAfter(true); imageView.setAnimation(translateAnimation); translateAnimation.start();Copy the code

Interpolator

Interpolator class that defines the speed of the animation transformation. Can realize the alpha/scale/translate/rotate animation acceleration, deceleration and repetition and so on. Interpolator class is actually an empty interface that inherits from TimeInterpolator. TimeInterpolator TimeInterpolator allows the animation to perform nonlinear motion transformations such as acceleration and rate limiting. There is only one method float getInterpolation(Float Input) in the interface. The value passed in is a value between 0.0 and 1.0, and the return value can be less than or greater than 1.0.

Add directly to the code above:

/ / directly use the SDK provides speed interpolation, translateAnimation. SetInterpolator (new AccelerateInterpolator (3 f));Copy the code

The effect is as follows:

AccelerateInterpolator is one of the interpolators provided by the SDK, starting slow and then faster. The SDK also comes with:

  • Decelerate, start fast and then decelerate
  • AccelerateDecelerateInterolator acceleration deceleration, after first started slowly, at the end of the middle speed
  • AnticipateInterpolator reversely, change a segment in the opposite direction first and then accelerate the play
  • AnticipateOvershootInterpolator reverse and beyond, change to the opposite direction, to speed up play, more objective value then move slowly to purpose
  • BounceInterpolator jump, the value will jump when it comes to the destination. For example, the destination value is 100, and the following values might be 85,77,70,80,90,100
  • Math.sin(2* mCycles* math.pi * input)
  • LinearInterpolator linear, linear uniform change
  • OvershootInterpolator goes over, finally goes over the destination value and then slowly changes to the destination value
  • PathInterpolator can define the path coordinate, and then run according to the path coordinate; Notice it’s not XY, it’s in one direction, so I can go from 0 to 1, and then I can bounce back to 0.5, and then I can bounce back to 0.7, and then I can bounce back to 0.3, and then at the end of time.

Let’s define a custom Interpolator: Interpolator

* @input the time phase of the animation, where 0 represents the beginning and 1 represents the end * @return the space phase of the animation, where below 0 represents the target not reached, Interpolator = new Interpolator() {@override public float getInterpolation(float input) { Return input * input + 0.2f; }}; translateAnimation.setInterpolator(interpolator);Copy the code

3. Property Animation

How to use tween animation to change the color of the ball from red to green? This is where Property Animation comes in.

If we add one sentence to the code above

ImageView. SetOnClickListener (v - > Toast. MakeText (this, "ball was click!" , Toast.LENGTH_SHORT).show());Copy the code

When the ball animation is over, click on the ball again, and the “ball was clicked!” will not appear. The toast. But if you click where you were, the Toast will appear.

This is because the tween animation only changes the display position of the ball, but the ball is still in its original position, that is, the coordinate property of the ball is not changed. Property animation can animate a View object by changing the property value of the View object or any other object that affects the display effect of the View object. In a certain interval of time, the object is animated on the property by changing the value and continuously assigning the value to the property of the object.

Evaluator

**Evaluator** is used to control how the property animation evaluates the property value.Copy the code
public interface TypeEvaluator<T> {
    public T evaluate(float fraction, T startValue, T endValue);
}
Copy the code

Based on the input initial value, end value, and a progress ratio, an attribute value is calculated for each progress.

Evaluator public static ValueAnimator ofArgb(int... values) { ValueAnimator anim = new ValueAnimator(); anim.setIntValues(values); anim.setEvaluator(ArgbEvaluator.getInstance()); return anim; } public class ArgbEvaluator implements TypeEvaluator {private static final ArgbEvaluator implements TypeEvaluator {private static final ArgbEvaluator implements TypeEvaluator sInstance = new ArgbEvaluator(); public static ArgbEvaluator getInstance() { return sInstance; } public Object evaluate(float fraction, Object startValue, float fraction, Object startValue, float fraction); Object endValue) {// Parameter description // Fraction: indicates the completion of the animation (from which to calculate the value of the current animation) // startValue, endValue: Int startInt = (Integer) startValue; int startA = (startInt >> 24) & 0xff; int startR = (startInt >> 16) & 0xff; int startG = (startInt >> 8) & 0xff; int startB = startInt & 0xff; int endInt = (Integer) endValue; int endA = (endInt >> 24) & 0xff; int endR = (endInt >> 16) & 0xff; int endG = (endInt >> 8) & 0xff; int endB = endInt & 0xff; // 1. Subtract the initial value from the final value and calculate the difference between them. // 2. Multiply the above difference by the fraction coefficient // 3. Add the initial value, Get the current value of the animation return (int) ((startA + (int) (fraction * (endA - startA))) < < 24) | (int) ((startR + (int) (fraction * (endR - startR))) << 16) | (int)((startG + (int)(fraction * (endG - startG))) << 8) | (int)((startB + (int)(fraction * (endB - startB)))); }}Copy the code

AnimationSet

A single animation effect is limited, and more use scenarios use multiple animation effects at the same time, that is, to combine different animations into a Set. Usage ————

XML file

<? The XML version = "1.0" encoding = "utf-8"? > <set xmlns:android="http://schemas.android.com/apk/res/android" android:ordering="sequentially" > <! -- indicates that the animations in the Set are in order --> <! Sequentially & together--> <! -- Sequentially: first, there will be a couple of animations in set --> <! <set android:ordering="together" > <! <objectAnimator android:duration="2000" Android :propertyName="translationX" Android :valueFrom="0" android:valueTo="300" android:valueType="floatType" > </objectAnimator> <objectAnimator android:duration="3000" android:propertyName="rotation" android:valueFrom="0" android:valueTo="360" android:valueType="floatType" > </objectAnimator> </set> <set android:ordering="sequentially" > <! <objectAnimator android:duration="1500" Android :propertyName="alpha" Android :valueFrom="1" android:valueTo="0" android:valueType="floatType" > </objectAnimator> <objectAnimator android:duration="1500" android:propertyName="alpha" android:valueFrom="0" android:valueTo="1" android:valueType="floatType" > </objectAnimator> < set > < set > / / about code referenced AnimatorSet animator = (AnimatorSet) AnimatorInflater. LoadAnimator (this, R.animator.set_animation); // Create a composite animation object & load the XML animation animator.settarget (mButton); // Set animator.start(); // Start the animationCopy the code

Java file

// Step 1: ObjectAnimator Translation = ObjectAnimator.ofFloat(mButton, "translationX", curTranslationX, "translationX") 300,curTranslationX); Rotate = ObjectAnimator.ofFloat(mButton, "Rotation ", 0f, 360f); ObjectAnimator alpha = objectAnimator. ofFloat(mButton, "alpha", 1f, 0f, 1f); // Step 2: Create an object AnimatorSet animSet = new AnimatorSet(); // Step 3: Create animset.play (Translation).with(rotate).before(alpha); animSet.setDuration(5000); // Step 4: start animset.start ();Copy the code

ObjectAnimator

The animation effect is inherited from ValueAnimator class by directly changing the property value of the object, that is, the underlying animation implementation mechanism is based on ValueAnimator class

Usage ————

Java code

public static ObjectAnimator setObjectAnimator(View view , String type , int start , int end , long time){ ObjectAnimator mAnimator = ObjectAnimator.ofFloat(view, type, start, end); // ofFloat() has two functions // Parameter Settings: The parameters are described as follows: // Object Object: the Object to be operated. // String property: the property of the Object to be operated. // float.... Values: // If there are two parameters a,b, then the animation effect is from a value to b value // If there are three parameters a,b,c, then the animation effect is from a value to b value to c value // and so on // How to transition from the initial value to the end value, Objectanimator.offloat () is the system's built-in floating-point evaluator. Manimator.setrepeatcount (ValueAnimator.infinite); // Set the number of animation repeats = number of replays +1 // When the number of animation plays = infinite; // Set the duration for the animation to run manimator.setDuration (time); Manimator.setstartdelay (0); manimator.setStartDelay (0); Manimator.setrepeatmode (valueAnimator.restart); / / ValueAnimator. RESTART (default) : positive sequence playback / / ValueAnimator. The REVERSE: REVERSE playback. / / set difference, mAnimator setInterpolator (new LinearInterpolator()); return mAnimator; }Copy the code

XML (need to be placed in the Animator folder of res)

<? The XML version = "1.0" encoding = "utf-8"? > <set xmlns:android="http://schemas.android.com/apk/res/android"> <ObjectAnimator android:valueFrom="1" android:valueTo="0" android:valueType="floatType" android:duration = "800" android:propertyName="alpha"/> </set> Animator mAnim = AnimatorInflater.loadAnimator(this, R.animator.animator_1_0); mAnim.setTarget(fabHomeRandom); mAnim.start();Copy the code

Each frame callback AnimatorUpdateListener. Update new onAnimationUpdate (ValueAnimator animation) method

Transition Animation

The first is the XML resource file approach

<set xmlns:android="http://schemas.android.com/apk/res/android" > <translate android:duration="2000" android:fromXDelta="30" android:fromYDelta="30" android:toXDelta="-80" android:toYDelta="300" /> <! Translate the int value of the animation: FromXDelta is the position on the X coordinate at the beginning of the animation; toXDelta is the position on the X coordinate at the end of the animation; fromYDelta is the position on the Y coordinate at the beginning of the animation; toYDelta is the position on the Y coordinate at the end of the animation. </set> </set> </set> </set> </set> </set>Copy the code

The second way: code

rotate.setDuration(durationMillis);
rotate.setFillAfter(true);
ivImage.setAnimation(rotate);
Copy the code