效果图
实现代码
public class RingWave extends View {private List<Wave> mWaveList = new ArrayList<>();private int[] colors = new int[]{Color.RED, Color.BLUE, Color.GREEN, Color.YELLOW};private Handler mHandler = new Handler(){@Overridepublic void handleMessage(Message msg) {flushData();invalidate();if (!mWaveList.isEmpty()){mHandler.sendEmptyMessageDelayed(0,50);}}};private void flushData() {ArrayList<Wave> removeList = new ArrayList<>();for (Wave wave : mWaveList){wave.radius += 3;wave.paint.setStrokeWidth(wave.radius/3);if (wave.paint.getAlpha() < 0){removeList.add(wave);continue;}int alpha = wave.paint.getAlpha();alpha -= 5;if (alpha < 0) alpha = 0;wave.paint.setAlpha(alpha);}mWaveList.removeAll(removeList);}public RingWave(Context context) {this(context, null);}public RingWave(Context context, AttributeSet attrs) {this(context, attrs, 0);}public RingWave(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);}@Overrideprotected void onDraw(Canvas canvas) {for (Wave wave : mWaveList){canvas.drawCircle(wave.cx, wave.cy, wave.radius, wave.paint);}}@Overridepublic boolean onTouchEvent(MotionEvent event) {switch (MotionEventCompat.getActionMasked(event)){case MotionEvent.ACTION_DOWN:case MotionEvent.ACTION_MOVE:addPoint((int)event.getX(), (int)event.getY());break;}return true;}private void addPoint(int x, int y) {if (mWaveList.isEmpty()){addWave(x, y);mHandler.sendEmptyMessageDelayed(0,50);}else {Wave lastWave = mWaveList.get(mWaveList.size() - 1);if (Math.abs(x - lastWave.cx) > 10 || Math.abs(y - lastWave.cy) > 10){addWave(x, y);}}}private void addWave(int x, int y) {Wave wave = new Wave();wave.cx = x;wave.cy = y;Paint paint = new Paint();paint.setStyle(Paint.Style.STROKE);paint.setStrokeWidth(wave.radius/3);paint.setAlpha(255);paint.setAntiAlias(true);int colorIndex = (int) (Math.random()*4);paint.setColor(colors[colorIndex]);wave.paint = paint;mWaveList.add(wave);}private class Wave{public int cx;public int cy;public int radius;public Paint paint;}}
布局文件
<?xml version="1.0" encoding="utf-8"?><com.google.widget.view.RingWave xmlns:android="/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"></com.google.widget.view.RingWave>
public class RingWaveActivity extends AppCompatActivity {@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_wave);SpannableString title = new SpannableString("水波纹");title.setSpan(new ForegroundColorSpan(Color.WHITE),0,title.length(),Spannable.SPAN_INCLUSIVE_EXCLUSIVE);ActionBar actionBar = getSupportActionBar();actionBar.setTitle(title);}}