首先声明,该效果并不是用动画实现的,而是用自定义View实现的,在onDraw方法里面调用invalidate()函数,实现气泡上升效果
气泡类:
- private class Bubble {
- /** 气泡半径 */
- private int radius;
- /** 上升速度 */
- private float speedY;
- /** 平移速度 */
- private float speedX;
- /** 气泡x坐标 */
- private float x;
- /** 气泡y坐标 */
- private float y;
- }
复制代码 另起线程生成气泡:
- if (!starting) {
- starting = true;
- new Thread() {
- public void run() {
- while (true) {
- try {
- Thread.sleep(random.nextInt(3) * 300);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- Bubble bubble = new Bubble();
- int radius = random.nextInt(30);
- while (radius == 0) {
- radius = random.nextInt(30);
- }
- float speedY = random.nextFloat()*5;
- while (speedY < 1) {
- speedY = random.nextFloat()*5;
- }
- bubble.setRadius(radius);
- bubble.setSpeedY(speedY);
- bubble.setX(width / 2);
- bubble.setY(height);
- float speedX = random.nextFloat()-0.5f;
- while (speedX == 0) {
- speedX = random.nextFloat()-0.5f;
- }
- bubble.setSpeedX(speedX*2);
- bubbles.add(bubble);
- }
- };
- }.start();
- }
复制代码 绘制渐变背景和气泡:
- Paint paint = new Paint();
- // 绘制渐变正方形
- Shader shader = new LinearGradient(0, 0, 0, height, new int[] {
- getResources().getColor(R.color.blue_bright),
- getResources().getColor(R.color.blue_light),
- getResources().getColor(R.color.blue_dark) },
- null, Shader.TileMode.REPEAT);
- paint.setShader(shader);
- canvas.drawRect(0, 0, width, height, paint);
- paint.reset();
- paint.setColor(Color.WHITE);
- paint.setAlpha(200);
- List<Bubble> list = new ArrayList<Bubble>(bubbles);
- for (Bubble bubble : list) {
- if (bubble.getY() - bubble.getSpeedY() <= 0) {
- bubbles.remove(bubble);
- } else {
- int i = bubbles.indexOf(bubble);
- if (bubble.getX() + bubble.getSpeedX() <= bubble.getRadius()) {
- bubble.setX(bubble.getRadius());
- } else if (bubble.getX() + bubble.getSpeedX() >= width
- - bubble.getRadius()) {
- bubble.setX(width - bubble.getRadius());
- } else {
- bubble.setX(bubble.getX() + bubble.getSpeedX());
- }
- bubble.setY(bubble.getY() - bubble.getSpeedY());
- bubbles.set(i, bubble);
- canvas.drawCircle(bubble.getX(), bubble.getY(),
- bubble.getRadius(), paint);
- }
- }
复制代码 解决了36楼问题:楼主 ,跑了下DEMO, 屏幕关闭后线程还在跑,但是CANVAS不刷新了,重新亮屏后所有的气泡挤在一起,时间一长会OOM吧
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。