Reprint Please specify source: http://blog.csdn.net/guolin_blog/article/details/44171115
Hello everyone, welcome to continue back to Android properties animation full parse. In the previous article, we learned some advanced techniques for property animation, including high-level usage of valueanimator and objectanimator, and there are, of course, some other advanced techniques waiting for us to learn. Therefore, this article on the entire property animation complete parsing series end, to learn the rest of the very important advanced techniques.
In addition, the code used in this article is based on the previous article, if you have not read the previous article, it is recommended to refer to the first reading of the Android property animation full parsing (medium), Valueanimator and Objectanimator advanced usage .
The use of Interpolator
Interpolator this thing is difficult to translate, literal translation of the words is the meaning of the tween, its main function is to control the rate of change of animation, such as to achieve a nonlinear motion animation effect. So what is the animated effect of nonlinear motion? That is, the rate of animation changes is not constant, such as acceleration and deceleration motion are non-linear motion.
However, Interpolator is not a new technology in property animation, actually there has been a interpolator interface since the beginning of Android 1.0, and the previous tweened animation is of course supporting this feature. Just a new Timeinterpolator interface is added to the property animation, which is used for compatibility with the previous interpolator, which allows all past interpolator implementation classes to be brought directly to the property animation. So let's take a look at all the implementation classes for the Timeinterpolator interface now, as shown in:
As you can see, the Timeinterpolator interface already has a lot of implementation classes, and these are all built-in Android systems and we can use the interpolator directly. Each interpolator has its own implementation effect, such as Accelerateinterpolator is a interpolator of accelerating motion, And Decelerateinterpolator is a slow motion of the interpolator.
I think the careful friend should have already discovered, in the previous two articles we have learned all the attribute animation, actually is not in carries on one kind of thread movement. For example, the values printed in the "Up" article using Valueanimator are as follows:
It can be seen that the first value changes significantly slower, only 0.0 of the beginning of the print 4 times, then began to accelerate, the final stage began to slow down, so we can clearly see this first acceleration after the deceleration of the interpolator.
Then take a look at the function of moving the ball and changing the color in the "medium" article, as shown in:
From the obvious, we can see that the small ball at the beginning of the movement speed is relatively slow, and then gradually accelerate, the middle part of the movement speed is relatively fast, then began to slow down, and finally slowly stop. In addition, the color change is the same law, the first color changes in the relatively slow, the middle color changes quickly, the final stage of the color change is relatively slow.
From the above points we can summarize a conclusion, the use of property animation, the system default Interpolator is actually a first acceleration after the deceleration of the interpolator, the corresponding implementation class is Acceleratedecelerateinterpolator.
Of course, we can also easily modify this default property and replace it with a built-in interpolator for any system. Take the code in the "middle" article for example, the Startanimation () method in Myanimview is the entrance to the animated effect, here we make a slight change to the coordinates of the point object, and let it become a vertical drop effect, the code looks like this:
private void Startanimation () {point startPoint = new Point (GetWidth ()/2, RADIUS); Point endPoint = new Point (GetWidth ()/2, 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 (+); Anim.start ();}
The main point here is to change the coordinate values in the point constructor, so now the animation of the ball motion should be dropped from the top of the center of the screen to the bottom. But now by default, the speed of the ball must be accelerated and slowed down, which is not in line with the common law of physics, if the ball as a free fall, then the rate of decline should be more and more fast. How can we change this default behavior? In fact, it is very simple, call Animator's Setinterpolator () method, this method requires the implementation of an instance of the Timeinterpolator interface, so for example, we want to achieve a small ball drop more and more quickly effect, You can use Accelerateinterpolator, as shown in the following code:
private void Startanimation () {point startPoint = new Point (GetWidth ()/2, RADIUS); Point endPoint = new Point (GetWidth ()/2, 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.setinterpolator (new Accelerateinterpolator (2f)); Anim.setduration (2500); Anim.start ();}
The code is simple, call the Setinterpolator () method, and then pass in an instance of Accelerateinterpolator, noting that Accelerateinterpolator's constructor can receive a float-type parameter, This parameter is used to control the acceleration. Now run the code and the effect looks like this:
OK, the effect is very obvious, indicating that we have successfully replaced the default interpolator,accelerateinterpolator is actually effective. But now the animation effect looks still strange, because a small ball from a very high place dropped to the ground directly on the static, which is not in line with the physical law, the ball hit the ground should be rebound, and then fall again, then bounce up again, and then fall again, in order to repeat, finally still. Of course we can write it ourselves, but more complicated, fortunately, the Android system has provided such a interpolator, we just need to simply replace it to complete the above description of the effect, the code is as follows:
private void Startanimation () {point startPoint = new Point (GetWidth ()/2, RADIUS); Point endPoint = new Point (GetWidth ()/2, 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.setinterpolator (New Bounceinterpolator ()); Anim.setduration (+); Anim.start ();}
As can be seen, we just replaced the set of Interpolator with Bounceinterpolator instance, and Bounceinterpolator is a kind of interpolator that can simulate the law of physics and realize the effect of repeated bouncing. In addition, the overall animation time is slightly lengthened, as the ball bounces back a little longer than before. Now run the code again, as shown in the following:
Ok! The effect is still very good. So here we just selected a few systems to achieve good interpolator, because the built-in interpolator very much, not one by one to explain, we can use some of the other interpolator to see the effect.
However, we will only use the system to provide good interpolator, we clearly to their own requirements is too low, since it is to learn the advanced use of property animation, then it is natural to study it thoroughly. Let's look at what Interpolator's internal implementation mechanism is and try to write a custom interpolator.
First look at the interface definition for Timeinterpolator, as shown in the code below:
/** * A time Interpolator defines the rate of change of a animation. This allows animations * to has non-linear motion, such as acceleration and deceleration. */public interface Timeinterpolator {/** * Maps a value representing the elapsed fraction of a animation to a Val UE that represents * the interpolated fraction. This interpolated value was then multiplied by the change in * value of a animation to derive the animated value at th E Current elapsed animation time. * * @param input A value between 0 and 1.0 indicating our current point * in the animation where 0 Represen TS the start and 1.0 represents * the end * @return the interpolation value. This value can is more than 1.0 for * interpolators which overshoot their targets, or less than 0 for * Interpolators that undershoot their targets. */float Getinterpolation (float input);}
OK, the interface is still very simple, there is only one getinterpolation () method. We are interested in a detailed understanding of this interface through comments, here I simply explained that the Getinterpolation () method receives an input parameter, the value of this parameter will continue to change as the animation runs, but its changes are very regular, is based on the set animation duration of the constant increase, the range of change is 0 to 1. That is, when the animation starts with the value of input is 0, to the end of the animation when the value of input is 1, and the middle value is the animation with the duration of the time between 0 to 1 changes.
Speaking of this input value, I think a lot of friends might associate with the fraction value we used in the "medium" article. So what's the relationship or difference between input and fraction here? The answer is simple, and the value of input determines the value of the fraction. The value of input is passed into the Getinterpolation () method after the system has been computed, and then we can implement the algorithm in the Getinterpolation () method by ourselves, which calculates a return value based on the value of input. And the return value is fraction.
Therefore, the simplest case is that the input value and the fraction value are the same, this situation because the input value is constant increase, so the value of fraction is also increased at a constant speed, so the motion of the animation is also uniform. The linearinterpolator built into the system is a kind of uniform motion interpolator, so let's look at how its source code is implemented:
/** * An interpolator where the rate of change is constant */@HasNativeInterpolatorpublic class Linearinterpolator extends Baseinterpolator implements Nativeinterpolatorfactory {public linearinterpolator () { } Public Linearinterpolator (context context, AttributeSet attrs) { } public float getinterpolation (float input) { return input; } /** @hide * /@Override public long Createnativeinterpolator () { return Nativeinterpolatorfactoryhelper.createlinearinterpolator (); }}
Here we only look at the Getinterpolation () method, this method does not have any logic, that is, the input value passed in the parameter is returned directly, so the value of fraction is equal to the value of input, this is uniform motion interpolator implementation way.
Of course this is the simplest kind of interpolator implementation, and let's look at a slightly more complicated one. Now that we all know that the system is using Acceleratedecelerateinterpolator by default, let's look at its source code, as shown below:
/** * an Interpolator where the rate of change starts and ends slowly but accelerates through the middle. * */@HasNativeInterpolatorpublic class Acceleratedecelerateinterpolator implements Interpolator, nativeinterpolatorfactory {public acceleratedecelerateinterpolator () {} @SuppressWarnings ({"Unuseddeclarati On '}) public Acceleratedecelerateinterpolator (context context, AttributeSet attrs) {} public float Getinterp Olation (float input) {return (float) (Math.Cos ((input + 1) * Math.PI)/2.0f) + 0.5f; }/** @hide */@Override public long Createnativeinterpolator () {return nativeinterpolatorfactoryhelper.c Reateacceleratedecelerateinterpolator (); }}
The code is not much longer, but the logic in the Getinterpolation () method has become significantly more complex, instead of simply returning input from the parameter, a more complex mathematical operation is performed. So here we analyze its algorithm implementation, you can see that the algorithm mainly uses the cosine function, because the value of input range is 0 to 1, then the value range of the Cos function is π to 2 π. The result of the cos (π) is that the result of -1,cos (2π) is 1, then this value is divided by 2 plus 0.5, and the resulting value returned by the Getinterpolation () method is still between 0 and 1. Only after the cosine operation, the final result is no longer constant speed increase, but experienced a first acceleration after the deceleration process. We can draw the execution of this algorithm by way of a graph, as shown in the result:
As you can see, this is an S-type graph, when the horizontal axis changes from 0 to 0.2, the ordinate changes in the amplitude is very small, but then began to accelerate significantly, the final horizontal axis from 0.8 to 1 when the change in the amplitude of the ordinate has become very small.
OK, through the analysis of the source code of Linearinterpolator and Acceleratedecelerateinterpolator, we have a relatively clear understanding of the internal implementation mechanism of Interpolator, So let's start by trying to write a custom interpolator.
Writing custom Interpolator The main difficulty is in the mathematical calculation, because I am not very good at maths, so here also write a simple point of interpolator to show you. Now that the property animation default Interpolator is a way to speed up and slow down, here's a simple modification to make it a way to slow down and accelerate. Create a new Decelerateaccelerateinterpolator class and let it implement the Timeinterpolator interface, as shown in the following code:
public class Decelerateaccelerateinterpolator implements timeinterpolator{ @Override public float Getinterpolation (float input) { float result; if (input <= 0.5) { result = (float) (Math.sin (Math.PI * input))/2; } else { result = (float) (2-MATH.S In (Math.PI * input))/2; } return result;} }
This code uses the sine function to achieve the first deceleration after the acceleration of the function, because the sine function of the initial radian value is very large, just as the cosine function is the opposite, and with the increase in radians, the value of the sine function will gradually become smaller, so that the effect of deceleration. When the radian is greater than Π/2, the whole process is reversed, now the sine function of the radian change value is very small, gradually with the radian continues to increase, the change value is more and more large, radian to π when the end, so from 0 over to π, also realized the first deceleration after the acceleration effect.
We can also draw the execution of this algorithm through a graph, as shown in the following:
As you can see, this is also an S-shaped graph, except that the direction of the curve is just the opposite. From which we can clearly see, the beginning of the vertical axis of change is very large, and then gradually become smaller, the horizontal axis to 0.5 when the amplitude of the ordinate changes toward zero, and then with the horizontal axis continues to increase the amplitude of the change in the scale and began to become larger, indeed is the first deceleration after the accelerated effect.
Now we will replace the Decelerateaccelerateinterpolator in the code as follows:
private void Startanimation () {point startPoint = new Point (GetWidth ()/2, RADIUS); Point endPoint = new Point (GetWidth ()/2, 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.setinterpolator (New Decelerateaccelerateinterpolator ()); Anim.setduration (+); Anim.start ();}
It is very simple to pass an instance of Decelerateaccelerateinterpolator into the Setinterpolator () method. Run the code again, as shown in the following:
Ok! The motion of a small ball is really the effect of slowing down and accelerating, which means that our custom interpolator is already working properly. Through such a degree of learning, we believe that the property animation Interpolator understanding and use have reached a more profound level.
The use of Viewpropertyanimator
Viewpropertyanimator is not really a high-level skill, it is very simple to use, but with all the properties of the previous learning of the animation of the knowledge of different, It is not introduced in the 3.0 system, but a new feature added to the 3.1 system, so here we take it as the finishing part of the entire property animation series.
As we all know, the mechanism of property animation is no longer designed for view, but rather a mechanism for constantly manipulating values to assign values to specified properties of the specified object. However, in the vast majority of cases, I believe that people are mostly still animation of the view. The Android development team is also aware of this, and it is a bit too impersonal to provide a more convenient usage for the animation of the view, which complements the viewpropertyanimator mechanism in the Android 3.1 system.
Let's review the previous usage, for example, if we want a textview to become transparent from the regular state, it can be written like this:
Objectanimator animator = Objectanimator.offloat (TextView, "alpha", 0f); Animator.start ();
Does it look complicated? It's not as complicated as it seems, but it's really not easy to understand. We're going to pass the view, property, and change values of the operation into the Objectanimator.offloat () method, although it doesn't seem to be a few lines of code, but it's not quite like the object-oriented thinking we're using.
So here's a look at how to use viewpropertyanimator to achieve the same effect, Viewpropertyanimator provides a more understandable, more object-oriented API, as shown here:
Textview.animate (). Alpha (0f);
It's very simple! But Textview.animate () How is this method going? The animate () method is a new method on the Android 3.1 system, the return value of this method is a Viewpropertyanimator object, which means that we can invoke its various methods to achieve the animation effect after we get the object. Here we call the Alpha () method and go to 0, which means that the current textview is turned into a transparent state.
What do you think? It's much easier to understand than using Objectanimator,viewpropertyanimator's usage. In addition, Viewpropertyanimator can easily combine multiple animations, for example, if we want the TextView to move to the 500,500 coordinate point, it can be written like this:
Textview.animate (). x (500);
As can be seen, Viewpropertyanimator is to support concatenating usage, we want to let TextView move to the position of the horizontal axis 500 when the X (500) method is called, and then let the textview move to ordinate 500 this position when the call Y (500) This way, all the animations that you want to combine are stitched together in such a concatenating way that all the animations will be executed.
So how do you set the duration of the animation to run? Very simple, but also by concatenating way to set up, for example, we want to let the animation run for 5 seconds, you can write:
Textview.animate (). x (a). Y (+). Setduration (5000);
In addition, the first part of this article Interpolator technology we can also apply to Viewpropertyanimator above, as follows:
Textview.animate (). x (a). Y (+). Setduration (Setinterpolator) (New Bounceinterpolator ());
The usage is simple and the same is the way of using concatenating. I believe everyone has experienced now, viewpropertyanimator in fact, there is no too much skill to say, usage is basically the same, need to use what function on concatenating, so more usage everyone just need to look at the document, see also support which features, There are interfaces that can be called on.
In addition to usage, there are a few details about viewpropertyanimator that you should be aware of:
- The entire Viewpropertyanimator function is built on the new animate () method of the view class, which creates and returns an instance of Viewpropertyanimator, followed by all methods of the call, All of the properties that are set are done through this instance.
- It is noted that when using viewpropertyanimator, we have not called the start () method from beginning to end, because the new interface uses the function of the implicit start animation, as long as we finish the animation definition, the animation will start automatically. And this mechanism is also effective for the combination animation, as long as we constantly concatenating new methods, then the animation will not be executed immediately, until all the methods set on the Viewpropertyanimator are executed, the animation will automatically start. Of course, if you don't want to use this default mechanism, we can also explicitly invoke the start () method to start an animation.
- All interfaces of Viewpropertyanimator are designed using concatenating syntax, and each method's return value is its own instance, so a method can be called directly concatenating another method to invoke it, so that all functions are threaded together, We can even complete the animation of any complexity with just one line of code.
OK, so up to here, the entire series of fully parsed Android property animations is all over, thank you for your patience to see the last.
First time to get blog update reminders, as well as more technical information sharing, welcome to follow my public number, sweep the QR code below or search number Guolin_blog, you can pay attention to.
Android Property Animation full parsing (bottom), Interpolator and Viewpropertyanimator usage