import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.View; /** * 基类 */ public abstract class BaseView extends View { private MyThread thread; private boolean running = true; public BaseView(Context context, AttributeSet attrs) { super(context, attrs); } public BaseView(Context context) { super(context); } protected abstract void drawSub(Canvas canvas); protected abstract void logic(); protected abstract void init(); class MyThread extends Thread { @Override public void run() { init(); while (running) { logic(); postInvalidate(); try { Thread.sleep(30); } catch (InterruptedException e) { e.printStackTrace(); } } } } @Override protected final void onDraw(Canvas canvas) { if (thread == null) { thread = new MyThread(); thread.start(); } else { drawSub(canvas); } } @Override protected void onDetachedFromWindow() { running = false; super.onDetachedFromWindow(); } }
1)简单描述单个雨点的行为。
绘制下雨场景的个体,雨点(直线);
让直线动起来;
处理边界问题;
1 import android.content.Context; 2 import android.graphics.Canvas; 3 import android.graphics.Paint; 4 import android.util.AttributeSet; 5 6 public class RainView extends BaseView { 8 private float startX; 9 private float startY; 10 private float stopX; 11 private float stopY; 12 private float sizeX; 13 private float sizeY; 14 private Paint paint; 15 16 public RainView(Context context, AttributeSet attrs) { 17 super(context, attrs); 19 // 角度。 20 sizeX = 10; 21 sizeY = 30; 22 // 以下是 初始化直线的坐标。 23 startX = 100; 24 startY = 0; 25 // 改变 角度的直线。 26 stopX = startX + sizeX; 27 stopY = startY + sizeY; 28 29 paint = new Paint(); 30 // 把直线 设置成白色。 31 paint.setColor(0xffffffff); 32 } 33 34 public RainView(Context context) { 35 super(context); 36 } 37 38 @Override 39 protected void drawSub(Canvas canvas) { 40 // 绘制一条直线 41 canvas.drawLine(startX, startY, stopX, stopY, paint); 42 } 43 44 @Override /* 让直线动起来 **/ 45 protected void logic() { 46 47 //倍率,通过倍率来改变速度。 48 float opt = 0.5f; 49 50 startX += sizeX * opt; 51 stopX += sizeX * opt; 52 53 startY += sizeY * opt; 54 stopY += sizeY * opt; 55 56 // 当直线走出屏幕的时候,变为初始位置。 57 if (startY > getHeight()) { 58 startX = 100; 59 startY = 0; 60 stopX = startX + 10; 61 stopY = startY + 30; 62 } 63 } 64 65 }
2)完善雨点行为和构造下雨场景。
构造雨点对象;
雨点大小设置;
速度设置;
角度设置等 添加多个雨点;
3)在xml中定义可以控制下雨的属性。
抽离可以在xml中影响的属性;
在代码中解析样式属性并使用其控制雨点变化;
时间: 2024-11-02 16:56:44