Animation: Interpolator usage and customization details

Animation: Interpolator usage and customization details

[[438230]]

Preface

Property animation can animate a certain property, and the interpolator (TimeInterpolator) and estimator (TypeEvaluator) play an important role in it;

So today we will learn about the interpolator TimeInterpolator;

1. Introduction to interpolators

1. What is Interpolator used for?

  • Interpolator is used to modify the animation effect and define the rate of change of the animation;
  • The corresponding interface class in the Android source code is TimeInterpolator, which inputs a uniformly changing value between 0 and 1;
  • You can get the change curves between 0 and 1 such as uniform speed, positive acceleration, negative acceleration, and irregular acceleration;

2. Application scenarios

  • Achieve animation effects of non-linear motion;
  • Non-linear motion means that the rate of change of animation is not constant, such as the animation effects of acceleration and deceleration;
  • Custom interpolators are required to implement complex curve animations, customize rebound effects, etc.

3. Interpolator types provided by the Android system

  • AccelerateDecelerateInterpolator is slow at the beginning and end of the animation, and accelerates in the middle
  • AccelerateInterpolator
  • AnticipateInterpolator starts backwards and then swings forward
  • AnticipateOvershootInterpolator starts by going backwards and then forwards a certain value before returning to the final value.
  • BounceInterpolator bounces when the animation ends
  • CycleInterpolator The animation loops a specific number of times, with the rate changing along a sine curve.
  • DecelerateInterpolator
  • LinearInterpolator changes at a constant rate
  • OvershootInterpolator throws forward a certain value and then returns to the original position

2. Interpolator Application

There are two ways to use interpolators: in XML and in code

1. xml

When using an interpolator in an XML animation file, you need to set the corresponding interpolator resource ID set by the system.

  1. <?xml version= "1.0" encoding= "utf-8" ?>
  2. < set xmlns:android= "http://schemas.android.com/apk/res/android" >
  3. <alpha
  4. android:fromAlpha= "1.0"  
  5. android:toAlpha= "0.1"  
  6. android:duration= "2000"  
  7. android:repeatMode= "reverse"  
  8. android:repeatCount= "infinite"  
  9. android:interpolator= "@android:anim/linear_interpolator" />
  10. </ set >

2. Use in code

  • When the code uses an interpolator, you only need to create the corresponding interpolator object and then set it to the animation object; you can also load the interpolator configured in the XML file;
  • Use the view's setInterpolator(Context context, @AnimRes @InterpolatorRes int resID) to set the interpolator;
  1. //Create a gradient transparency animation from transparent to fully opaque
  2. AlphaAnimation alphaAnimation = new AlphaAnimation(0.1f, 1.0f);
  3. //Set animation duration
  4. alphaAnimation.setDuration(5000);
  5. //Set the animation repeat mode
  6. alphaAnimation.setRepeatMode(AlphaAnimation.REVERSE);
  7. //Set the number of animation plays
  8. alphaAnimation.setRepeatCount(AlphaAnimation.INFINITE);
  9. //Set the uniform speed interpolator
  10. alphaAnimation.setInterpolator(new LinearInterpolator());
  11. // Enable the specified type of animation for View
  12. imageView.startAnimation(alphaAnimation)
  • Using Android's built-in interpolator can meet most animation needs;
  • If the interpolator provided by the system cannot meet your needs, you can also customize the interpolator;

3. Custom Interpolator

1. Implementation

  • Custom interpolators need to implement the Interpolator or TimeInterpolator interface and override the getInterpolation() method;
  • Tween animation implements Interpolator interface; property animation implements TimeInterpolator interface;
  • The TimeInterpolator interface is newly added in property animation to be compatible with the Interpolator interface, which allows all previous Interpolator implementation classes to be used directly in property animation;

The Interpolator interface and TimeInterpolator interface are described as follows:

  1. //Interpolator interface
  2. public interface Interpolator {
  3. // There is only one method inside: getInterpolation()
  4. float getInterpolation( float input) {
  5. // Parameter description
  6. // The input value range is 0-1, and changes evenly with the animation progress (0% - 100%)
  7. // When the animation starts, the input value = 0; when the animation ends, the input = 1
  8. // The middle value increases evenly between 0 and 1 as the animation progresses (0% - 100%)
  9. ...// Interpolator calculation logic
  10. return xxx;
  11. // The returned value is the fraction value used by the estimator to continue calculating, which will be explained in detail below
  12. }
  13. // TimeInterpolator interface
  14. public interface TimeInterpolator {
  15. float getInterpolation( float input){
  16. // The input value range is 0-1, and changes evenly with the animation progress (0% - 100%)
  17. ...// Interpolator calculation logic
  18. };
  19. }

The key to custom interpolators is to calculate the percentage of the current property value change through logical calculations based on the progress of the animation (0%-100%).

2. Custom interpolator

Write a custom Interpolator: decelerate first and then accelerate

  1. /*
  2. * Implement Interpolator interface as required
  3. * TestInterpolator.java
  4. */
  5. public class TestInterpolator implements TimeInterpolator {
  6. @Override
  7. public   float getInterpolation( float input) {
  8. float result;
  9. if (input <= 0.5) {
  10. result = ( float ) (Math.sin(Math.PI * input)) / 2;
  11. // Use the sine function to achieve the function of deceleration first and then acceleration. The logic is as follows:
  12. // Because the initial radian change of the sine function is very large, it is exactly the opposite of the cosine function
  13. // As the radian increases, the change value of the sine function will gradually decrease, thus achieving the effect of deceleration.
  14. // When the radian is greater than π/2, the whole process is reversed. Now the radian change value of the sine function is very small. As the radian continues to increase, the change value becomes larger and larger, and ends when the radian reaches π. In this way, the transition from 0 to π achieves the effect of deceleration first and then acceleration.
  15. } else {
  16. result = ( float ) (2 - Math.sin(Math.PI * input)) / 2;
  17. }
  18. return result;
  19. // The returned result value = the animation progresses with a trend of first slowing down and then accelerating
  20. }
  21. }
  22. /*
  23. * Steps to set up use
  24. * Test.java
  25. */
  26. // Create an animation object: Here we take Button as an example
  27. mButton = (Button) findViewById(R.id.Button);
  28. // Get the current button position
  29. float curTranslationX = mButton.getTranslationX();
  30. // Create animation object & set animation
  31. ObjectAnimator animator = ObjectAnimator.ofFloat(mButton, "translationX" , curTranslationX, 300,curTranslationX);
  32. // means:
  33. // The animation object is mButton
  34. // The property of the object being animated is X-axis translation
  35. // The animation effect is: moving from the current position to x=1500 and then moving to the initial position
  36. // Set the interpolator set in step 1: decelerate first and then accelerate
  37. animator.setInterpolator(new TestInterpolator());
  38. // Start the animation
  39. animator.start();

3. Bezier curve interpolator

(1) First use the Bezier curve value generation tool to obtain the desired curve value

  • Tool website: https://cubic-bezier.com/;
  • Drag the two points on the left image to adjust the graphics to meet the effect;
  • Click the Go button to see the movement of the red and blue blocks and adjust the effect you want;
  • Apply the 4 parameters to the following code;

(2) Code application

  1. ObjectAnimator animator = ObjectAnimator.ofFloat(mButton, "translationX" , curTranslationX, 300,curTranslationX);
  2. EaseCubicInterpolator interpolator = new EaseCubicInterpolator(0.31f, 0.85f,0.77f, 0.14f);
  3. animator.setInterpolator(interpolator)

(3) Bezier curve interpolator

  1. import android.graphics.PointF;
  2. import android.view.animation.Interpolator ;
  3. /**
  4. * Easing cubic curve interpolator. (Based on cubic Bezier curve)
  5. */
  6. public class EaseCubicInterpolator implements Interpolator {
  7. private final static   int ACCURACY = 4096;
  8. private int mLastI = 0;
  9. private final PointF mControlPoint1 = new PointF();
  10. private final PointF mControlPoint2 = new PointF();
  11. /**
  12. * Set the two middle control points
  13. *
  14. * Online tool: http://cubic-bezier.com
  15. *
  16. * @param x1
  17. * @param y1
  18. * @param x2
  19. * @param y2
  20. */
  21. public EaseCubicInterpolator( float x1, float y1, float x2, float y2) {
  22. mControlPoint1.x = x1;
  23. mControlPoint1.y = y1;
  24. mControlPoint2.x = x2;
  25. mControlPoint2.y = y2;
  26. }
  27. @Override
  28. public   float getInterpolation( float input) {
  29. float t = input;
  30. // Approximately solve the value of t [0,1]
  31. for ( int i = mLastI; i < ACCURACY; i++) {
  32. t = 1.0f * i / ACCURACY;
  33. double x = cubicCurves(t, 0, mControlPoint1.x, mControlPoint2.x, 1);
  34. if (x >= input) {
  35. mLastI = i;
  36. break;
  37. }
  38. }
  39. double value = cubicCurves(t, 0, mControlPoint1.y, mControlPoint2.y, 1);
  40. if (value > 0.999d) {
  41. value = 1;
  42. mLastI = 0;
  43. }
  44. return ( float ) value;
  45. }
  46. /**
  47. * Find the value of a certain dimension of a point on a cubic Bezier curve (four control points).<br>
  48. * <p>
  49. *
  50. * @param t value [0, 1]
  51. * @param value0
  52. * @param value1
  53. * @param value2
  54. * @param value3
  55. * @return  
  56. */
  57. public   static   double cubicCurves( double t, double value0, double value1,
  58. double value2, double value3) {
  59. double value;
  60. double u = 1 - t;
  61. double tt = t * t;
  62. double uu = u * u;
  63. double uuu = uu * u;
  64. double ttt = tt * t;
  65. value = uuu * value0;
  66. value += 3 * uu * t * value1;
  67. value += 3 * u * tt * value2;
  68. value += ttt * value3;
  69. return value;
  70. }
  71. }

Summarize

To achieve complex animation effects, you need to customize the interpolator. In fact, the interpolator is still a learning algorithm;

Let's all cheer together;

<<:  Some Apple iPhone 13/12 iOS 15 devices damage car Bluetooth hands-free system

>>:  Gartner: Opt-out rates for mobile app tracking will drop from 85% to 60% by 2023

Recommend

Attention! Heavy rain + thunderstorm + hail is coming!

Today (June 14), heavy rainfall continues in the ...

WeChat iOS 7.0.12 is officially launched, dark mode is here

WeChat version 7.0.12 is officially launched. Aft...

Is the Apple Watch a failure so far?

[[145129]] According to media reports today, anal...

Does breathing through the mouth really ruin your appearance?

We need to breathe every moment, but have you eve...

Judgment on marketing trends in 2021!

The past year has been extremely magical, and I b...

Do you know the real reason why lithium battery performance deteriorates?

Lithium-ion batteries are now widely used in mobi...

Tu Mi Character Design Issue 2 2021 [Good quality with courseware]

Tu Mi Character Design Issue 2 2021 [Good quality...

How to promote Xiaohongshu notes to become popular?

It is indeed difficult for a new account to becom...

How to cold start brand operation and promotion?

What is the cold start of a new brand? New brand,...