public class MyWaveView extends View{ private ArrayList<Wave> list; private int[] colors = {Color.RED,Color.BLUE, Color.DKGRAY,Color.GREEN,Color.YELLOW}; public boolean isRunning = false; public MyWaveView(Context context) { this(context,null); } public MyWaveView(Context context, AttributeSet attrs) { this(context, attrs,0); } public MyWaveView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); list = new ArrayList<MyWaveView.Wave>(); } //用户用手触摸时触发 @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: int x = (int) event.getX(); int y = (int) event.getY(); //创建水波纹,并放到集合中; addWave(x, y); break; default: break; } return true; } public void addWave(int x,int y ){ Wave wave = new Wave(); //确定圆心 wave.rX = x; wave.rY = y; //确定半径 radius: 0---> Paint paint = new Paint(); paint.setColor(colors[(int)(Math.random()*5)]); paint.setAntiAlias(true); paint.setStyle(Paint.Style.STROKE); wave.paint = paint; addWaveToList(wave,x,y); } private void addWaveToList(Wave wave,int x,int y) { if(list.size() == 0){ list.add(wave); isRunning = true; handler.sendEmptyMessage(0); }else{ if(Math.abs(x - (list.get(list.size() -1)).rX) > 50 || Math.abs(y - (list.get(list.size() -1)).rY) > 50){ list.add(wave); } } } Handler handler = new Handler(){ public void handleMessage(android.os.Message msg) { refreshPaint(); invalidate(); if(isRunning){ handler.sendEmptyMessageDelayed(0, 18); } }; }; private void refreshPaint(){ for(int i = 0;i< list.size();i++){ Wave wave = list.get(i); wave.radius += 4; int alpha = wave.paint.getAlpha(); alpha -= 5; if(alpha < 5 ){ alpha = 0; } wave.paint.setAlpha(alpha); if(alpha == 0){ list.remove(i); } wave.radius = wave.radius + 3; wave.paint.setStrokeWidth(wave.radius/3); if(list.size() == 0){ isRunning = false; } } } //水波纹对象 public class Wave{ public int radius; public int rX; public int rY; public Paint paint; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); for(int i = 0; i < list.size();i++ ){ Wave wave = list.get(i); canvas.drawCircle(wave.rX, wave.rY, wave.radius, wave.paint); } } }
时间: 2024-10-14 09:08:12