标签:
新建工程UsingSurfaceView
新建一个类GameView继承至SurfaceView并实现Callback接口
添加构造方法,并复写Callback的三个未实现的方法
创建一个容器Contanier承载所有的View
public class Contanier {
private List<Contanier> children=null;
public Contanier(){
children = new ArrayList<Contanier>();
}
public void draw(Canvas canvas){
childrenView(canvas);
for (Contanier c:children) {
c.draw(canvas);
}
}
public void childrenView(Canvas canvas){
}
public void addChildrenView(Contanier child){
children.add(child);
}
public void removeChildrenView(Contanier child){
children.remove(child);
}
}
新建一个Contanier子类Rect
public class Rect extends Contanier{
private Paint paint = null;
public Rect(){
paint=new Paint();
paint.setColor(Color.RED);
}
//复写childrenView方法
public void childrenView(Canvas canvas) {
super.childrenView(canvas);
canvas.drawRect(0, 0, 100, 100, paint);
}
}
再新建一个Contanier子类
public class Circle extends Contanier{
private Paint paint=null;
public Circle(){
paint=new Paint();
paint.setColor(Color.BLUE);
}
@Override
public void childrenView(Canvas canvas) {
// TODO Auto-generated method stub
super.childrenView(canvas);
canvas.drawCircle(50, 50, 50, paint);
}
}
返回类GameView进行初始化
private Contanier contanier;
private Rect rect;
private Circle circle;
public GameView(Context context) {
super(context);
contanier = new Contanier();
rect = new Rect();
circle = new Circle();
rect.addChildrenView(circle);
contanier.addChildrenView(rect);
//添加回调
getHolder().addCallback(this);
}
在surfaceChanged方法中调用draw方法
在MainActivity中
setContentView(new GameView(this));
使绘制的图形移动起来
修改Contanier类
private float x = 0,y = 0;
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 void draw(Canvas canvas){
canvas.save();
canvas.translate(getX(), getY());
childrenView(canvas);
for (Contanier c:children) {
c.draw(canvas);
}
canvas.restore();
}
修改Rect类的childrenView方法
public void childrenView(Canvas canvas) {
super.childrenView(canvas);
canvas.drawRect(0, 0, 100, 100, paint);
this.setY(getY()+1);
}
对移动操作 修改类GameView
private Timer timer = null;
private TimerTask task = null;
public void startTimer(){
timer = new Timer();
task = new TimerTask() {
@Override
public void run() {
draw();
}
};
timer.schedule(task, 100, 100);
}
public void stopTimer(){
if (timer != null) {
timer.cancel();
timer = null;
}
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
startTimer();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
stopTimer();
}
标签:
原文地址:http://www.cnblogs.com/cityking/p/a022.html