Respect the original! Reprint Please specify source: http://blog.csdn.net/cyp331203/article/details/41114551
Today we are using Android custom controls to achieve a more interesting effect: sliding water ripples. Let's take a look at the final:
Figure A
The effect is still very dazzling, the meal to a mouthful, the road to step by step, here we will the whole process into a few steps to achieve
One, the realization of click on the appearance of water ripple single ring effect:
Figure II
As a matter of routine, it's a custom control, and here we're just going to get this control to fill up the entire screen (a previous article that's not familiar to custom controls:Android custom Control Series II: Custom Switch button (i)). Observing this effect, we find that it is necessary to rewrite the Ontouchevent and OnDraw methods by getting the coordinates of the touch in the Ontouchevent, and then drawing the graph we need with this coordinate value as the center of the map, which is the OnDraw method of the call.
1. Create a new project, define a Waterwave class, inherit from view, as a custom control; write out the custom control in the manifest file and fill the parent form directly.
2. In the Waterwave class, implement its two-parameter constructor:
Package Com.example.waterwavedemo.ui;import Android.content.context;import Android.graphics.canvas;import Android.graphics.color;import Android.graphics.paint;import Android.os.handler;import Android.os.Message;import Android.util.attributeset;import Android.view.motionevent;import Android.view.view;public class WaterWave extends View {... */* 1, two-parameter constructor */public Waterwave (context context, AttributeSet Attrs) {Super (context, attrs); alpha = 0;radius = 0 ; Initpaint ();} ...}
3, to use the custom control, then generally need to specify its size, here we only need to fill the form, so the default Onmeasure method can be used:
/** * Onmeasure method, determines the size of the control, which uses the default */@Overrideprotected void onmeasure (int widthmeasurespec, int heightmeasurespec) {// TODO auto-generated Method Stubsuper.onmeasure (Widthmeasurespec, heightmeasurespec);}
4, Draw this custom graphic, rewrite the OnDraw method, here because we need to draw a circle, so write:
@Override/** * The method of drawing the required graphics, this method is more critical */protected void OnDraw (canvas canvas) {canvas.drawcircle (Xdown, Ydown, radius, paint );}
The parameters Xdown and Ydown are member variables, which represent the x and Y coordinates when pressed, and the corresponding point of the coordinate is the center of the circle to be drawn; the radius parameter is also a member variable that represents the radius of the ring to be drawn;
See here also need a paint, is the paint type of the brush object, which is defined as a member variable, because the OnDraw method is called the first time the custom control is displayed, so this paint needs us in the constructor of the two parameters to initialize, Otherwise, a null pointer exception is reported, so we'll write another Initpaint () method here to initialize our paint:
/** * Initialize paint */private void Initpaint () {/* * Create a new brush */paint = new paint ();p Aint.setantialias (true);p Aint.setstrokewidth (width);//set is a circular way to draw Paint.setstyle (Paint.Style.STROKE); System.out.println ("alpha=" + Alpha);p Aint.setalpha (Alpha); SYSTEM.OUT.PRINTLN ("Obtained transparency:" + paint.getalpha ());p Aint.setcolor (color.red);}
5. Touch timed Refresh
After the OnDraw method, we can already draw this circle, but the real problem is that we want to achieve a click to draw a circle in the click Position, then we definitely need to get the coordinates of the click Xdown and Ydown, So it's definitely necessary to rewrite the Ontouchevent method, and we need to let the transparency be the least transparent (alpha=255) when we press it, and in the process of drawing, let the radius of the ring expand, while minimizing the opacity until fully transparent (alpha=0) , this changing process needs to re-refresh the state and redraw the graphics every once in a while, so we use handler to handle it:
@Override/** * Touch Event Method */public Boolean ontouchevent (Motionevent event) {super.ontouchevent (event); switch ( Event.getaction ()) {case MotionEvent.ACTION_DOWN:radius = 0;alpha = Max_alpha;width = Radius/4;xdown = (int) Event.getx ( ); ydown = (int) event.gety (); handler.sendemptymessage (0); Break;case motionevent.action_move:break;case Motionevent.action_up:break;default:break;} return true;}
As you can see, we have only implemented the logic inside the Action_down, set the radius radius to 0 at each press, the transparency alpha to be completely opaque, and the width to 0, and get the x and y coordinates pressed, After the use of handler sent an empty message, let handler to achieve the timing of the refresh State and drawing the work, we want to let the transparency of the ring when the Alpha pick up to 0 time will not continue to automatically refresh the timing, otherwise, each time the handlemessage is refreshed the state value , and then draw the graphic:
Private Handler Handler = new Handler () {@Overridepublic void Handlemessage (Message msg) {super.handlemessage (msg); Switch (msg.what) {case 0:flushstate (); invalidate (); if (alpha! = 0) {//If the opacity is not to 0, continue to refresh, Otherwise stop refreshing handler.sendemptymessagedelayed (0, 50);} Break;default:break;}} /** * Refresh status */private void Flushstate () {radius + 5;alpha-= 10;if (Alpha < 0) {alpha = 0;} System.out.println ("alpha=" + alpha); width = Radius/4;paint.setalpha (alpha);p aint.setstrokewidth (width);}};
We can see that in handler, we rewrite the Handlemessage method, in Msg.what=0, we call the Flushstate () method to refresh the state, and the Invalidate () method to draw the graph, Then use handler.sendemptymessagedelayed (0, 50) to repeat the above work every 50 milliseconds, where invalidate () is provided by Android, and Flushstate () needs to be implemented by ourselves;
According to our needs, each time the status of the Refresh Work flushstate (), we need to do the following several things:
(1) To increase the radius
(2) To reduce the transparency and set it to paint;
(3) The width of the ring increases and is set to paint
(4) For transparency, the maximum value is 255, but if the transparency is reduced to less than 0, for example, 1, then the value of alpha will not be 1, but 255+ (-1) = 254, so we need to add a judgment condition to prevent alpha<0
/** * Refresh status */private void Flushstate () {radius + 5;alpha-= 10;if (Alpha < 0) {alpha = 0;} System.out.println ("alpha=" + alpha), width = Radius/4;paint.setalpha (alpha);p aint.setstrokewidth (width);}
6. Add some initialization work in the constructor of the two parameters:
Public Waterwave (context context, AttributeSet Attrs) {Super (context, attrs); alpha = 0;radius = 0;initpaint ();}
At this point, our first step is basically done
Second, the realization of multiple click ring at the same time, the effect of refreshing:
From the face map two , we can not find that, no matter how to click, the screen will only have a circle at the same time, this is because each time we click, we reset the center, and all the parameters of the circle are member variables, are shared; If you click again when the previous circle does not disappear, it will increase the speed at which the new circle becomes larger, because the handler.sendemptymessagedelayed (0,50) method is used to repeatedly trigger this method on the second click. Makes the handler.sendemptymessagedelayed () overlap of two clicks effective, so that the actual interval is much less than 50 milliseconds, so the refresh rate is much faster
So now we have to solve the two small problems, to achieve the effect of:
The idea of solving these two small problems:
1. For all water ripple Circle sharing parameters:
The method is to create a new inner wave, which holds the parameters for each circle, each of which corresponds to a wave object, and then, in the OnDraw method, redraws all the circle views at the same time, then a list collection wavelist is needed to hold all the wave objects. Easy traversal.
2, for the Handler.sendemptymessagedelayed method in the subsequent click of the time is constantly called, resulting in the problem of more and more rapid refresh.
Here you can set a member variable Boolean Isstart; the flag is not pressed for the first time, because when we press the first time, we must want to start a timed refresh, call handler.sendemptymessagedelayed, so that the state of the ring constantly changing. But for subsequent clicks, we actually just want it to be refreshed immediately and added to the Wavelist collection without having to send a handler message to invoke handler.sendemptymessagedelayed. So when we set it to true at the very beginning and set it to false at the first click, when it's set to false, there's a third problem:
3, for the Wavelist collection, if you have been clicking to add Wave objects to the collection, then will undoubtedly make this collection more and more large, this is what we do not want to see, we want the transparency value of the ring Alpha to 0, which is completely transparent, Remove it from the wavelist so that it can be reclaimed by garbage collection, so that if you stop after clicking a few points, the point will automatically disappear (the alpha value is reduced to 0), then the corresponding Wave object will also be removed from the wavelist, the size of the wavelist will become 0, At this point we can stop the Handler.sendemptymessagedelayed method from continuing to be called, while the Isstart can be reset to true. So when is Isstart set to False? We can set this to False when the flushstate is refreshed because it indicates that the first click has been pressed when the status is refreshed. Then, under the Action_dwon condition of the Ontouchevent method, if Isstart is true, the handler message is sent, which means that the first click is not sent but the wave object is added to the wavelist. Because the first time the call Flushstate has set the Isstart to False.
Because of the large changes, the code is as follows:
Package Com.example.waterwavedemo.ui;import Java.util.arraylist;import Java.util.collections;import java.util.List ; Import Android.content.context;import Android.graphics.canvas;import Android.graphics.color;import Android.graphics.paint;import Android.os.handler;import Android.os.message;import Android.util.AttributeSet; Import Android.view.motionevent;import Android.view.view;public class Waterwave extends View {/** * waveform list */private Lis T<wave> wavelist;/** * Maximum opacity, completely opaque */private static final int max_alpha = 255;protected static final int Flush_all = -1;private Boolean Isstart = true;///**//* Pressed when x-coordinate//*///private int xdown;///**//* When pressed y coordinates//*///private int ydown;///**//* Used to represent the radius of the ring//*///private float radius;//private int alpha;/* * 1, two parameter constructors */public Waterwave (Context Conte XT, AttributeSet Attrs) {Super (context, attrs); wavelist = Collections.synchronizedlist (New arraylist<wave> ());} /** * Onmeasure method, determines the size of the control, which uses the default */@Overrideprotected void onmeasure (int wIdthmeasurespec, int heightmeasurespec) {super.onmeasure (Widthmeasurespec, heightmeasurespec);} @Override/** * Draw a method that requires graphics, this method is more critical */protected void OnDraw (canvas canvas) {//Redraw all rings for (int i = 0; i < wavelist.size () ; i++) {Wave wave = Wavelist.get (i); Canvas.drawcircle (Wave.xdown, Wave.ydown, Wave.radius, Wave.paint);}} /** * Initialize Paint */private paint initpaint (int alpha, float width) {/* * Create a new brush */paint paint = new Paint ();p Aint.setantiali As (true);p aint.setstrokewidth (width);//Set is a ring-shaped paint.setstyle (Paint.Style.STROKE);//System.out.println ("Alpha = "+ Alpha");p Aint.setalpha (alpha);//System.out.println ("obtained transparency:" + paint.getalpha ());p Aint.setcolor (color.red); return paint;} Private Handler Handler = new Handler () {@Overridepublic void Handlemessage (Message msg) {super.handlemessage (msg); Switch (msg.what) {case 0:flushstate (); invalidate (); if (wavelist! = null && wavelist.size () > 0) {handler.send Emptymessagedelayed (0, 50);} break;default:break;}}};/ * * Refresh status */private void FlusHstate () {for (int i = 0; i < wavelist.size (); i++) {Wave wave = Wavelist.get (i); if (Isstart = = False && Wave.a Lpha = = 0) {wavelist.remove (i); wave.paint = Null;wave = null;continue;} else if (Isstart = True) {Isstart = false;} Wave.radius + = 5;wave.alpha = 10;if (Wave.alpha < 0) {Wave.alpha = 0;} Wave.width = Wave.radius/4;wave.paint.setalpha (Wave.alpha); Wave.paint.setStrokeWidth (wave.width);}} Private Paint paint;//private float width; @Override/** * Method of Touch Event */public Boolean ontouchevent (Motionevent event) {sup Er.ontouchevent (event), switch (Event.getaction ()) {case MotionEvent.ACTION_DOWN:Wave wave = new Wave (); Wave.radius = 0; Wave.alpha = Max_alpha;wave.width = Wave.radius/4;wave.xdown = (int) event.getx (); wave.ydown = (int) event.gety (); wave.p aint = Initpaint (Wave.alpha, wave.width); if (wavelist.size () = = 0) {Isstart = true;} System.out.println ("isstart=" + Isstart); Wavelist.add (wave);//After clicking, scrub the graphics invalidate (); if (Isstart) { Handler.sendemptymessage (0);} Break;caseMotionevent.action_move:break;case Motionevent.action_up:break;default:break;} return true;} The private class Wave {int Wavex;int wavey;/** * is used to represent the radius of the ring */float radius; Paint paint;/** * Press the X coordinate */int xdown;/** * When pressed y coordinates */int ydown;float width;int Alpha;}
Three, achieve full effect (click and move, Color random, circle size change speed)
Is the same as Tuyi, mainly to do a few small places:
1, let ontouchevent inside of Action_down and action_move response to the same event, in fact, is to remove the action_down break; then write the processing code to the subsequent action_move.
2. Create a new array of member variables colors, put the color you want, and then in the Initpaint method set color, use Paint.setcolor (colors[(int) (Math.random () * ( COLORS.LENGTH-1)]);
3, control the change trend of the waveform, this look at personal hobbies, I do this: in the flushstate:
Wave.radius + = Wavelist.size ()-i;wave.width = (WAVE.RADIUS/3); Wave.paint.setStrokeWidth (wave.width);//Wave.alpha-= 10;if (Wave.alpha < 0) {Wave.alpha = 0;} Wave.width = Wave.radius/4;wave.paint.setalpha (Wave.alpha);
This completes the custom water ripple effect. The problem is that if the simulator, fast sliding, there will be a lag, on my mobile phone Nexus5, still smooth, should be memory-independent, and may also do some optimizations.
Android Custom Control series five: Custom Fancy water ripple effect