I saw an iOS component Pendulumview on the Internet and realized the animation effect of the pendulum. Because the native progress bar is really not good-looking, you want to be able to customize the view to achieve this effect, can later be used to load the page's progress bar.
Don't say much nonsense, first on the effect chart
The black side of the bottom is recorded accidentally, can be ignored.
Since it's a custom view, we'll follow the standard process, step one, custom attributes
Custom Properties
Create a property file
Create a new Attrs.xml file in the Res->values directory of the Android project, which reads as follows:
<?xml version= "1.0" encoding= "Utf-8"?>
<resources>
<declare-styleable name= "Pendulumview" >
<attr name= "globenum" format= "integer"/> <attr name= "Globecolor"
format= "color"/>
<attr name= "Globeradius" format= "Dimension"/> <attr name= "
Swingradius" format= "Dimension"/>
</declare-styleable>
</resources>
Where the Declare-styleable Name property is used to reference the property file in code. The name attribute, which is generally written in our custom view class name, is more intuitive.
Using Styleale, the system can complete a lot of constants (int[] arrays, subscript constants, etc. to write, simplifying our development work, such as the following code used in the R.styleable.pendulumview_golbenum and so is the system for our automatic generation.
The Globenum attribute represents the number of small balls, globecolor the color of the ball, globeradius the radius of the ball, Swingradius the swing radius.
Reading property values
Reading property values through Typedarray in the custom View construction method
The property value can also be obtained by AttributeSet, but if the property value is a reference type, only the ID is obtained, and the real property value is still to be obtained by resolving the ID, and Typedarray directly helps us to do the work.
Public Pendulumview (context, AttributeSet attrs, int defstyleattr) {Super (context, attrs, defstyleattr);
Use TypedArray to read a custom property value TypedArray ta = context.getresources (). Obtainattributes (Attrs, R.styleable.pendulumview);
int count = Ta.getindexcount ();
for (int i = 0; i < count; i++) {int attr = Ta.getindex (i);
Switch (attr) {Case r.styleable.pendulumview_globenum:mglobenum = Ta.getint (attr, 5);
Break Case R.styleable.pendulumview_globeradius:mgloberadius = Ta.getdimensionpixelsize (attr, (int) Typedvalue.applyd
Imension (TYPEDVALUE.COMPLEX_UNIT_PX, Getresources (). Getdisplaymetrics ()));
Break
Case R.styleable.pendulumview_globecolor:mglobecolor = Ta.getcolor (attr, Color.Blue);
Break Case R.styleable.pendulumview_swingradius:mswingradius = Ta.getdimensionpixelsize (attr, (int) Typedvalue.applyd Imension (TYPEDVALUE.COMPLEX_UNIT_PX, GEtresources (). Getdisplaymetrics ());
Break } ta.recycle ();
Avoid problems with next read Mpaint = new Paint ();
Mpaint.setcolor (Mglobecolor);
}
Overriding the Onmeasure () method
@Override
protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {
super.onmeasure ( Widthmeasurespec, Heightmeasurespec);
int widthmode = Measurespec.getmode (widthmeasurespec);
int widthsize = measurespec.getsize (widthmeasurespec);
int heightmode = Measurespec.getmode (heightmeasurespec);
int heightsize = measurespec.getsize (heightmeasurespec);
Height for ball radius + swing radius
int height = Mgloberadius + Mswingradius;
Width for 2* swing radius + (Ball number-1) * Ball diameter
int width = Mswingradius + Mgloberadius * 2 * (mGlobeNum-1) + Mswingradius;
If the measurement mode is exactly, use recommended values directly, such as exactly (general handling wrap_content), using your own computed width-height
setmeasureddimension (widthmode = measurespec.exactly)? Widthsize:width, (Heightmode = = measurespec.exactly)? heightsize:height);
}
which
int height = Mgloberadius + Mswingradius;
<pre name= "code" class= "java" >int width = Mswingradius + Mgloberadius * 2 * (mGlobeNum-1) + Mswingradius;
Used to handle the at_most of the measurement mode, which is generally the width and height setting of the custom view to Wrap_content, at this point the height of view is computed by the number of balls, radii, and the radius of the swing, as shown below:
For example, the size of the view is the red rectangular area of the following figure 5.
Overriding the OnDraw () method
@Override
protected void OnDraw (Canvas Canvas) {
super.ondraw (Canvas);
Draw other balls except left and right two balls for
(int i = 0; i < mGlobeNum-2 i++) {
canvas.drawcircle (Mswingradius + (i + 1) * 2 * Mglo Beradius, Mswingradius, Mgloberadius, mpaint);
if (Mleftpoint = null | | mrightpoint = NULL) {
//initialization of the most about two small ball coordinates
mleftpoint = new Point (Mswingradius, Mswingradius);
mrightpoint = new Point (Mswingradius + Mgloberadius * 2 * (mGlobeNum-1), Mswingradius);
Open oscillating animation
startpendulumanimation ();
}
Draw left and right two small balls
canvas.drawcircle (Mleftpoint.x, Mleftpoint.y, Mgloberadius, mpaint);
Canvas.drawcircle (Mrightpoint.x, Mrightpoint.y, Mgloberadius, mpaint);
The OnDraw () method is the key to customizing the view, drawing the view's display in the body of the method. The code first draws off the left-most right side of the ball outside the small, and then the coordinates of the two small balls to judge, if it is the first time to draw, the coordinate values are empty, then initialize the two small ball coordinates, and open animation. Finally, the x,y value of Mleftpoint,mrightpoint is plotted to draw about two balls.
Mleftpoint,mrightpoint are all Android.graphics.Point objects, using them only to store the X,y coordinate information of the left and right two small spheres.
Animate using Properties
public void Startpendulumanimation () {//Use property animation final Valueanimator Anim = valueanimator.ofobject (New Typeevaluat or () {@Override public Object evaluate (float fraction, object Startvalue, Object Endvalue) {//Parameter Frac
tion is used to indicate the degree of completion of the animation, and we calculate the current animation value based on it double angle = math.toradians (fraction);
int x = (int) ((mswingradius-mgloberadius) * Math.sin (angle));
int y = (int) ((mswingradius-mgloberadius) * Math.Cos (angle));
Point point = new Point (x, y);
return point;
}, New Point (), New Point ()); Anim.addupdatelistener (New Valueanimator.animatorupdatelistener () {@Override public void onanimationupdate (Va
Lueanimator animation) {Point point = (point) animation.getanimatedvalue ();
Get the current fraction value float fraction = anim.getanimatedfraction (); To determine whether it is fraction first to decrease and then increase, that is, whether in the upcoming swing state//In the upcoming upward swing when the switch ball if (lastslope && fraction > Mlastfraction)
{ Isnext =!isnext; ///By constantly altering the x,y coordinates of the left and right small ball to achieve the animation effect//Use Isnext to determine whether it should be left small ball movement, or the right-hand ball movement if (isnext) {//When the left small ball swing, right small ball
At the initial position mrightpoint.x = Mswingradius + Mgloberadius * 2 * (mGlobeNum-1);
Mrightpoint.y = Mswingradius;
Mleftpoint.x = Mswingradius-point.x;
Mleftpoint.y = Mgloberadius + point.y;
else {//when the right ball swings, the left side of the ball is placed at the initial position mleftpoint.x = Mswingradius;
Mrightpoint.y = Mswingradius;
Mrightpoint.x = Mswingradius + (mGlobeNum-1) * Mgloberadius * 2 + point.x;
Mrightpoint.y = Mgloberadius + point.y;
} invalidate ();
Lastslope = fraction < mlastfraction;
Mlastfraction = fraction;
}
});
Set permanent loop playback anim.setrepeatcount (valueanimator.infinite);
Set the loop mode to play Anim.setrepeatmode (Valueanimator.reverse) in reverse order;
Anim.setduration (200); Set up the tween to control the change rate of the animation anim.setinterpolator (new DecelerateinterpOlator ());
Anim.start ();
}
The use of Valueanimator.ofobject method is to be able to the point object to operate, more image specific. There is also the use of the Ofobject method of the custom Typeevaluator object, resulting in a fraction value, which is a decimal from 0-1. So the latter two parameters of the method (new Point ()), Endvalue (Startvalue) are not practical, or can be directly written, which is written mainly to facilitate understanding. Similarly, you can also use the Valueanimator.offloat (0f, 1f) method directly to obtain a decimal number that varies from 0-1.
Final Valueanimator anim = Valueanimator.ofobject (new Typeevaluator () {
@Override public
Object Evaluate (float Fraction, Object Startvalue, Object Endvalue) {
//parameter fraction is used to indicate the degree of completion of the animation, and we calculate the current animation value based on it
double angle = Math.toradians (fraction);
int x = (int) ((mswingradius-mgloberadius) * Math.sin (angle));
int y = (int) ((mswingradius-mgloberadius) * Math.Cos (angle));
Point point = new Point (x, y);
return point;
}
, New Point (), New Point ());
by fraction, we calculate the angle change when the ball swings, 0-90 degrees.
The value represented by Mswingradius-mgloberadius is the length of the Green Line in the figure, the swinging route, and the course of the center of the ball is an arc with a (Mswingradius-mgloberadius) radius, The change of x value is (Mswingradius-mgloberadius) *sin (angle), and the variable y-value is (Mswingradius-mgloberadius) *cos (angle)
The actual center coordinates of the corresponding ball are (mswingradius-x,mgloberadius+y)
The right small ball movement line is similar to the left, only is the direction is different. The actual center coordinates of the right small ball (Mswingradius + (mGlobeNum-1) * Mgloberadius * 2 + x,mgloberadius+y)
Visible the left and right sides of the ball is the same ordinate, only the horizontal axis is different.
float fraction = anim.getanimatedfraction ();
Determine if the fraction first decreases and then increases, that is, whether it is on the verge of swinging upward
//toggle the ball
if lastslope && fraction > mlastfraction on each impending upward swing
isnext =!isnext;
}
Record whether the last fraction was continuously reduced
Lastslope = fraction < mlastfraction;
Record the last fraction
mlastfraction = fraction;
These two codes are used to calculate when to toggle the motion of the ball, the animation set the loop playback, and the cycle mode for reverse playback, so the animation of a period that is the ball toss and the ball down process. The value of the fraction in the process is 0 to 1, and then 1 to 0. So when is the beginning of a new cycle of animation? is when the ball is about to throw, at this time to switch the movement of the ball, you can achieve the left side of the ball after the right ball thrown up, the right ball after the left side of the small ball cast animation effect.
So how do you capture this point in time?
The fraction value increases when the ball is thrown, and the fraction value decreases when the ball falls. The moment when the ball is about to be thrown is that the fraction is transformed from being reduced to an ever-increasing moment. The code records whether the last time the fraction is decreasing, and then compare this time the fraction is increasing, if two conditions are set up then switch the moving ball.
Anim.setduration ();
Set up a tween to control the change rate of the animation
Anim.setinterpolator (New Decelerateinterpolator ());
Anim.start ();
Set the duration of the animation to 200 milliseconds, and the reader can change the value to achieve the goal of modifying the speed of the ball swing.
Set the animation of the tween, because the ball is thrown is a gradual deceleration of the process, falling is a gradual acceleration of the process, so use decelerateinterpolator to achieve deceleration effect, in reverse play when the acceleration effect.
Start the animation, the pendulum effect of the custom view progress bar is achieved! Run quickly and see how it works!
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.