Detailed description of Property Anim and propertyanim
Preface:
In the previous article, the basis and comparison of traditional View animation and Property animation are briefly compared with the simple basis of Android animation system. In this article, we will conduct a comprehensive and in-depth discussion on PropertyAnimation, this article can be divided into two parts. The sixth part can be used as the demarcation point. The first five sections focus on the calculation process of the animation values of PropertyAnim. The introduction and comparison between ValueAnimator and ObjectAnimator and TimeInterpolation and TypeEvaluator are important, starting from the sixth part, I analyzed the entire animation computing and internal processing details from the perspective of source code, as well as the analysis of the NineOldAndroids open-source library of JakeWharton. If you think too much, you can tell them separately. If your understanding is inaccurate, please correct me.
Property Animation
The official saying is that Property Animation is a powerful Animation framework that can add Animation effects to almost all things. You can define an animation to change the attributes of any object, regardless of whether the object is on the screen or not. An Attribute animation changes an attribute value of an object (a field of an object) in a certain period of time ).
The property animation system provides the following attributes for an animation:
Duration: animation Duration
TimeInterpolation: an interface used to define the animation change rate. All interpolation devices must implement this interface, such as linear and non-linear interpolation.
TypeEvaluator: an interface used to define the calculation method of attribute values. The options include int, float, and color. The attribute values of the current time are calculated based on the start, end, and interpolation of the attribute.
Animation sets: an Animation set that can be used to apply multiple animations to an object at the same time. These animations can be played at the same time or set different latencies for different animations.
Frame refreash delay: the refresh time, that is, the number of times the attribute value is calculated. The default value is 10 ms. The final refresh time is also affected by system process scheduling and hardware.
Repeat Country and behavoir: Repeat times and modes, such as three, five, and infinite loop playback. This animation can be replayed continuously or reversely after playback.
I. How Property Animation works
1.1 example
Example 1: Linear Animation
The motion of the X attribute of an object is described below. The X coordinate of the object is moved from 0 to 40 pixel within 40 ms, refreshed every 10 ms, moved four times, and moved 40/4 = 10 pixel each time.
Example 2: Non-linear Animation
A simple understanding is non-uniform speed. The same 40 pixel, the same time, but the speed is different, the start and end speed is slower than the middle part, that is, acceleration first and then deceleration
1.2. Several important components of attribute Animation
TimeInterpolator implements the interface of the interpolation device for calculating interpolation.
The interface for calculating the property value of TypeAnimator.
ValueAnimator has implemented the TimeInterpolator and TypeAnimator interfaces to track the attributes related to the animation time, for example, how long an animation has been completed, the start, end, or attribute values of the current animation being executed.
1.3 animation computing process
Process 1: Calculate the completed animation score elapsed fraction
To execute an animation, you need to create a ValueAnimator and specify the start, end, and duration of the target object attribute. After start is called, ValueAnimator calculates a score between 0 and 1 Based on the completed animation time, representing the percentage of completed animation. 0 represents 0%, 1 represents 100%, for example, in Example 1, total time t = 40 MS, t = 10 MS is 0.25.
Process 2: Calculate the interpolation (animation change rate) interpolated fraction
After ValueAnimator finishes calculating the animation score, it calls the currently set TimeInterpolator to calculate an interpolated (interpolation) score. During the calculation, the percentage of completed animations is added to the new interpolation calculation. In Example 2, because the animation is slowly accelerated, its interpolation score is about 0.15, less than 0.25 of the completed animation score when t = 10 ms. In example 1, the interpolation score is always the same as the completed animation score.
For more information about interpolation, seeSection 2.3.
Process 3: Calculate the attribute value
After the interpolation score is calculated, ValueAnimator calls a proper TypeEvaluator Based on the interpolation score to calculate the attribute value in the motion.
The above analysis introduces two concepts:Completed animation scores(Elapsed fraction ),Interpolated fraction).
In Example 2 above, TimeInterpolator uses AccelerateDecelerateInterpolator, while its TypeEvaluator uses IntEvaluator.
After understanding the specific process, let's analyze its computing process. t = 10 ms:
Process 1:Calculated animation time score: t = 10 ms/40 ms = 0.25.
Process 2:Because AccelerateDecelerateInterpolator is used in the preceding example, the formula is as follows (input is the time factor), and the calculated interpolation is about 0.15:
public float getInterpolation(float input) { return (float)(Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f;}
Here, the Interpolator interface is directly inherited from TimeInterpolator, and there is no internal method, while TimeInterpolator only has one getInterpolation method, so all Interpolator only need to implement the getInterpolation method. The following is the source code of AccelerateDecelerateInterpolator:
public class AccelerateDecelerateInterpolator implements Interpolator { public AccelerateDecelerateInterpolator() { } @SuppressWarnings({"UnusedDeclaration"}) public AccelerateDecelerateInterpolator(Context context, AttributeSet attrs) { } public float getInterpolation(float input) { return (float)(Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f; }}
Process 3:Because its TypeEvaluator type is FloatEvaluator, the calculation formula is as follows. Because startValue = 0, the calculated attribute value is 0.15 * (40-0) = 6 pixel:
public Float evaluate(float fraction, Number startValue, Number endValue) { float startFloat = startValue.floatValue(); return startFloat + fraction * (endValue.floatValue() - startFloat);}
The parameters are the interpolation scores, start values, and end values of the previous step.
I believe that the entire animation computing process is very clear here.
The sixth part introduces the source code analysis in detail.Internal implementation of these three processes.
II. Introduction to APIs of related objects
Because the View Animation system has defined many interpolation devices in android. view. animation, you can apply them directly to your property Animation. Although Animator provides the basic framework for animation creation, you should not directly use this class because it only provides a few functions and needs to be expanded to fully support animation. The following describes the main types of property animation systems.
2.1 Animators
1. ValueAnimator
The main time series engines in property animation, such as animation time, start and end attribute values, and calculation methods of corresponding time attribute values. Contains all core functions for calculating animation values. It also contains the details and information of each animation time, whether an animation is repeated, whether to listen to update events, and so on. You can also set a custom computing type.
The entire Property Animation has two steps:
1. Calculate the property value
2. Set the attribute value for the target object, that is, apply and refresh the animation.
ValueAnimiator only completes Step 1. To complete step 2, you must listen to the attribute values calculated by ValueAnimator and modify the target object. You need to implement the ValueAnimator. onUpdateListener interface to process the animation logic of the object by yourself, for example:
ValueAnimator animation = ValueAnimator.ofFloat(0f, 1f);animation.setDuration(1000);animation.addUpdateListener(new AnimatorUpdateListener() {@Overridepublic void onAnimationUpdate(ValueAnimator animation) { Log.i("update", ((Float) animation.getAnimatedValue()).toString()); }});animation.setInterpolator(new CycleInterpolator(3));animation.start();
2. ObjectAnimator
It is inherited from ValueAnimator and allows you to specify the object to be animated and an attribute of the object. The new calculated valueAutomatically update attributes. That is to say, the two steps of Property Animation are implemented. In most cases, it is enough to use ObjectAnimator, because it makes the processing of the animation value of the target object easy, and you no longer need to write the animation update logic like ValueAnimator. However, ObjectAnimator has certain restrictions. For example, it requires the attribute of the target object to provide the specified processing method. At this time, you need to make a choice in ObjectAnimator and ValueAnimator according to your own needs, which implementation is easier. In the followingPart 3Important introduction.
3. AnimationSet
An animation set provides a combination of multiple animations and allows you to set the timing relationships of the animations in the group, such as simultaneous playback, sequential playback, or delayed playback. Elevator tells the property animation system how to calculate an attribute value. They get time series data from the Animator class, such as the start and end values, and calculate the animation attribute value based on the data.
4. TimeAnimator
It cannot directly implement the animation effect. It is a simple callback mechanism for the listener. In the onTimeUpdate callback method of the TimeListener interface, the animation duration and the interval between the last call are returned, there are no methods for duration, interpolation, and setting values. It is mainly used to handle each frame of an animation by Y its listener.
For more detailed analysis and selection in actual use, see section 3.
2.2 Evaluators
Evaluators tells the property animation system how to calculate an attribute value. They calculate the attribute values of an animation through the starting and ending values of the animation provided by Animator.
The property system provides the following Evaluators:
1. IntEvaluator
2. FloatEvaluator
3. ArgbEvaluator
These three calculators are provided by the system to calculate the int, float, and color attributes respectively.
4. TypeEvaluator
An interface used to customize the calculator. If your object property value type is not int, float, or color, you must implement this interface to define your own data type.
For more information, seePart 5: Use TypeEvaluator
2.3 Interpolators
Interpolation: a time function that defines the animation Variation Law.
The interpolation tool only needs to implement one method: getInterpolation (float input). Its function is to map the elapsed fraction changes from 0 to 1 to another interpolated fraction. The input parameter is the time point when the animation is executed normally, and the returned value is the time point when the user really wants it to be executed. The input parameter is {0, 1}, and the returned value is generally {0, 1 }. {0, 1} indicates the entire animation process. Decimal places such as 0.2 and 0.3 in the middle indicate the position in the whole animation (originally at a constant speed), which is actually a ratio. If the returned value is a negative number, it is executed in the opposite direction. If the returned value is greater than 1, it is executed beyond the normal direction. That is to say, an animation may fluctuate up or down the value you specified, most of the time it is within the range of the specified value.
GetInterpolation (float input) changes the default animation time point elapsed fraction. According to the time point interpolated fraction, the obtained value is different from the default time point, the principle of interpolation is to speed up or slow down by changing the actual animation execution time point, or delay the default animation time point in advance. The animation interpolation tool only modifies the animation execution time and does not modify the track.
Simply explain this method, that is, when the input time is to be executed, another time point is returned through Interpolator calculation, so that the system can execute an animation of another time.
The first step in the animation calculation process is to obtain the percentage of completed time elapsed fraction, that is, the input parameter of the getInterpolation method. Interpolation is the function of time, and interpolation is the function value. The source code of AccelerateDecelerateInterolator provided by Android animation is:
AccelerateDecelerateInterpolatorpublic float getInterpolation(float input) { return (float)(Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f;}
In the following figure, we can also see the function values corresponding to the Formula (Formula) of AccelerateDecelerate and its getInterpolation (input) method.
From:Http://cogitolearning.co.uk /? P = 1078. This article also introduces Android Property Anim. If you are interested, take a look.
Next we will further analyze it through the function diagram of AccelerateDecelerate.
This curve shows two animation calculation processes: the X axis is a time factor (the maximum value is 1, so the value on each X axis can be seen as a percentage ), that is, the value obtained in the first step of the animation computing process. The Y axis is the corresponding time interpolation, that is, the second step of the animation computing process. Another step is that the final attribute value is calculated using TypeEvaluator.
The following describes several interpolation devices:
AccelerateDecelerateInterolator accelerates and then slows down.
AccelerateInterpolator acceleration, slow intermediate acceleration at the beginning
DecelerateInterpolator slows down, starts fast, and then slows down
AnticipateInterpolator reversely, first changes to the opposite direction and then accelerates playback.
AnticipateOvershootInterpolator reversely goes beyond the target value, changes in the opposite direction, and then accelerates playback. It then slowly moves beyond the target value.
BounceInterpolator jumps when it is approaching the destination value. For example, if the destination value is 100, the following values may be 90,100
CycleIinterpolator loop. The animation loops for a certain number of times. The value changes to a sine function: Math. sin (2 * mCycles * Math. PI * input)
LinearInterpolator linear, linear and even change
OvershottInterpolator goes beyond the target value, and then slowly changes to the target value
TimeInterpolator: an interface that allows you to customize interpolator.
If these interpolation devices cannot meet your needs, you can use the TimeInterpolator interface to create your own interpolation devices. The following describes how LinearInterpolator computes interpolation. LinearInterpolator does not affect the percentage of completed animations.
LinearInterpolator
public float getInterpolation(float input) { return input;}
3. Apply animations
3.1 add an animation using ValueAnimator
The ValueAnimator class can specify a series of int, float, and color values for some animations. Obtain a ValueAnimator by calling the factory methods ofInt (), ofFloat (). ofObject.
ValueAnimator animation = ValueAnimator.ofFloat(0f, 1f);animation.setDuration(1000);animation.start();
The above code is invalid because there is no animation target shadow at all, and the calculated attribute value is not obtained in the ValueAnimator listener to update the target object, so there is no animation effect.
You need to specify a custom type for the animation:
ValueAnimator animation = ValueAnimator.ofObject(new MyTypeEvaluator(), startPropertyValue, endPropertyValue);animation.setDuration(1000);animation.start();
ValueAnimator uses the logic provided by MyTypeEvalutor to calculate the attribute values between the start and end of an animation with a length of MS, starting from the start method. The first code does not have a real effect on the object. You usually want to modify the animation object by calculating the calculated attribute value. However, ValueAnimator does not directly operate on an object or attribute. You need to implement an AnimatorUpdateListener listener in ValueAnimator to manually update the attribute value of the target object and process other important events in the animation lifecycle, such as frame update. After you implement the listener, you can use the getAnimateValue () method to obtain the animation value of a frame and then perform the update operation.