绘制容器类:
//图形绘制容器 public class Contanier { private List<Contanier> list; private float x=0,y=0; public Contanier(){ list=new ArrayList<Contanier>(); } public void draw(Canvas canvas){ canvas.save(); canvas.translate(getX(), getY()); childrenDraw(canvas); for(Contanier c : list){ c.draw(canvas); } canvas.restore(); } public void childrenDraw(Canvas canvas){ } public void addChildren(Contanier child){ list.add(child); } public void removeChildren(Contanier child){ list.remove(child); } public float getX() { return x; } public void setX(float x) { this.x = x; } public float getY() { return y; } public void setY(float y) { this.y = y; } }
绘制正方型类:
//绘制正方型 public class Rect extends Contanier { private Paint paint; public Rect(){ paint=new Paint(); paint.setColor(Color.RED); } @Override public void childrenDraw(Canvas canvas) { super.childrenDraw(canvas); canvas.drawRect(0, 0, 100, 100, paint); this.setY(getY()+1); } }绘制圆:
//绘制圆 public class Circle extends Contanier { private Paint paint; public Circle(){ paint=new Paint(); paint.setColor(Color.BLUE); } @Override public void childrenDraw(Canvas canvas) { super.childrenDraw(canvas); canvas.drawCircle(50, 50, 50, paint); } }绘制类:
public class GameView extends SurfaceView implements Callback{ private Contanier contaier; private Rect rect; private Circle circle; public GameView(Context context) { super(context); contaier=new Contanier(); rect=new Rect(); circle=new Circle(); rect.addChildren(circle); contaier.addChildren(rect); getHolder().addCallback(this); } private void draw(){ Canvas canvas=getHolder().lockCanvas(); canvas.drawColor(Color.WHITE); contaier.draw(canvas); getHolder().unlockCanvasAndPost(canvas); } private Timer timer=null; private TimerTask task=null; //开始后让其根据Y轴进行移动 private void startTimer(){ timer=new Timer(); task=new TimerTask() { @Override public void run() { draw(); } }; timer.schedule(task, 100,100); } private void stopTimer(){ if(timer!=null){ timer.cancel(); timer=null; } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceCreated(SurfaceHolder holder) { startTimer(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { stopTimer(); } }
MainActivity:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new GameView(this)); }
效果: