今天带来一篇自定义View的小案例,点击屏幕随机生成五颜六色的波浪效果。逻辑十分简单,Demo挺有趣,直接代码分享在下面:
public class MyWaveView extends View {
List<Wave> waveList = new ArrayList<MyWaveView.Wave>();
List<Wave> currentList = new ArrayList<MyWaveView.Wave>();
private int alpha;
int[] colors = new int[] { Color.BLUE, Color.RED, Color.GREEN, Color.YELLOW ,Color.GRAY,Color.LTGRAY};
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
flushData();
if (!waveList.isEmpty()) {// 集合若为空没必要发消息
// 发延时消息,形成循环
handler.sendEmptyMessageDelayed(0, 80);
}
// 刷新界面
invalidate();
}
};
private void flushData() {
for (Wave wave : waveList) {
// 半径增加
wave.radius += 3;
wave.paint.setStrokeWidth(wave.radius / 3);
alpha = wave.paint.getAlpha();
if (alpha <= 0) {
// 当前wave消失,集合移除该对象,放置内存溢出
currentList.add(wave);
continue;
}
// 透明度降低
alpha -= 5;
if (alpha < 0) {
alpha = 0;
}
wave.paint.setAlpha(alpha);
}
//统一移除
waveList.remove(currentList);
}
public MyWaveView(Context context) {
this(context, null);
}
public MyWaveView(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* 随机获取颜色值
*
* @return
*/
private int getRandomColor() {
Random random = new Random();
int n = random.nextInt(colors.length);
return colors[n];
}
@Override
protected void onDraw(Canvas canvas) {
for (Wave wave : waveList) {
canvas.drawCircle(wave.cx, wave.cy, wave.radius, wave.paint);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
int cx = (int) event.getX();
int cy = (int) event.getY();
initWave(cx, cy);
break;
default:
break;
}
return true;
}
/**
* 封装波浪信息
*
* @param cx
* @param cy
*/
private void initWave(int cx, int cy) {
if (waveList.isEmpty()) {// 第一次添加Wave对象
addWave(cx, cy);
// 发消息展示“动画”
handler.sendEmptyMessage(0);
} else {
//获取上一次的最后一个波浪实例
Wave lastWave = waveList.get(waveList.size() - 1);
if(Math.abs(cx - lastWave.cx)>8 || Math.abs(cy - lastWave.cy)>8){
addWave(cx, cy);
}
// 第一次已经发了消息,不必再去发消息
}
}
/**
* 创建Wave对象,并添加到集合
*
* @param cx
* @param cy
*/
private void addWave(int cx, int cy) {
Wave wave = new Wave();
wave.cx = cx;
wave.cy = cy;
Paint paint = new Paint();
paint.setColor(getRandomColor());
paint.setAntiAlias(true);
// Style.STROKE:表示空心
paint.setStyle(Style.STROKE);
wave.paint = paint;
waveList.add(wave);
}
/**
* 波纹的封装类,一个波纹代表一个对象
*
* @author lenovo
*
*/
public class Wave {
public float radius;
public int cx;
public int cy;
public Paint paint;
}
}
运行效果如下:
关注本专栏,不定期更新简单有趣的小案例哦~
打开微信搜索公众号 Android程序员开发指南 或者手机扫描下方二维码 在公众号阅读更多Android文章。
微信公众号图片:
作者:qq_32059827 发表于2017/2/3 15:32:33 原文链接
阅读:13 评论:0 查看评论