自定义一个类,继承View,直接上代码了,比较简单
public class MyRing extends View {
private List<Wave> listWave;// 波纹list
private int[] colors = { Color.BLUE, Color.GREEN, Color.YELLOW, Color.RED, Color.CYAN };
private final int MIDX = 13;
private final int MIDY = 13;
private boolean isRunning = false;// false 已经完成 true 开始画
public MyRing(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
/**
* 初始化数据
*/
private void initView() {
listWave = new ArrayList<MyRing.Wave>();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (int i = 0; i < listWave.size(); i++) {
canvas.drawCircle(listWave.get(i).cx, listWave.get(i).cy, listWave.get(i).radius, listWave.get(i).paint);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
int cx = (int) event.getX();
int cy = (int) event.getY();
chexkWave(cx, cy);
break;
default:
break;
}
return true;
}
/**
* 检查水滴
*
* @param cx
* @param cy
*/
private void chexkWave(int cx, int cy) {
if (listWave.size() == 0) {
isRunning = true;
addWave(cx, cy);// 添加水滴
handler.sendEmptyMessage(0);// 发送更新消息
} else {
Wave wave = listWave.get(listWave.size() - 1);
if (Math.abs(wave.cx - cx) > MIDX || Math.abs(wave.cy - cy) > MIDY) {
// 超过了间隔
addWave(cx, cy);
}
}
}
/**
* 添加水滴。初始化水滴信息
*
* @param cx
* @param cy
*/
private void addWave(int cx, int cy) {
Wave wave = new Wave();
wave.cx = cx;
wave.cy = cy;
wave.radius = 5;
Paint paint = new Paint();
paint.setAntiAlias(true);// 设置抗锯齿
Random random = new Random();
int colorItem = random.nextInt(5);
paint.setColor(colors[colorItem]);// 设置颜色
paint.setStyle(Style.STROKE);// 设置圆环
paint.setStrokeWidth(10);// 设置圆环宽度
paint.setAlpha(255);// 设置透明度 0-255 0是全透明
wave.paint = paint;
listWave.add(wave);
}
/**
* 刷新状态
*/
private void flushStats() {
for (int i = 0; i < listWave.size(); i++) {
Wave wave = listWave.get(i);
int alpha2 = wave.paint.getAlpha();
if (alpha2 == 0) {
listWave.remove(i);
continue;
}
alpha2 -= 10;
alpha2 = Math.max(0, alpha2);
wave.paint.setAlpha(alpha2);
wave.radius += 8;
wave.paint.setStrokeWidth(wave.radius / 3);
}
if (listWave.size() == 0) {
isRunning = false;
}
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
flushStats();
invalidate();// 执行刷新动作
// if (paint.getAlpha() > 0) {
// handler.sendEmptyMessageDelayed(0, 100);
// }
if (isRunning) {
handler.sendEmptyMessageDelayed(0, 100);
}
}
};
/**
* 使用默认的大小
*/
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
/**
* 定义波纹
*
* @author
*
*/
private class Wave {
// x轴坐标
private int cx;
// y轴坐标
private int cy;
// 圆环的半径
private float radius;
// 画笔
private Paint paint;
}