java位图不工作
我有一个代码,可以把一个物体向下移动,但它静止不动。有人能说什么不对吗
第一个代码
视图类显示了目标代码
import 安卓.app.Activity;
import 安卓.os.Bundle;
public class Game extends Activity {
Play View;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
View = new Play(this);
setContentView(View);
}
}
Secound代码
这是物体应该移动的代码
import 安卓.content.Context;
import 安卓.graphics.Bitmap;
import 安卓.graphics.BitmapFactory;
import 安卓.graphics.Canvas;
import 安卓.graphics.Color;
import 安卓.view.View;
public class Play extends View {
int Y=0;
Bitmap object;
public Play(Context context) {
super(context);
// TODO Auto-generated constructor stub object = BitmapFactory.decodeResource(getResources(), R.drawable.brid);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
canvas.drawColor(Color.GRAY);
canvas.drawBitmap(object, (canvas.getWidth()/2), Y, null);
if (Y < canvas.getHeight()){
Y +=10;
}else {
Y = 0;
}
}
}
# 1 楼答案
首先,不要将
Play
对象称为“视图”,因为它指的是Android类。把它命名为“playView”为了回答您的问题,当
onDraw()
完成时,View
不会重新绘制自身。要做到这一点,你应该在onDraw()
的末尾调用invalidate()
为了使画图流畅,我建议将其放入
Thread
中,并进行游戏循环以运行画图。查看SurfaceView
,因为这比从View
直接绘制到Canvas
要快# 2 楼答案
我不确定您希望发生什么,但是View.onDraw()不会自动为您调用多次,一旦您的视图呈现,它不会再次被调用,直到有东西请求重新绘制,通常使用View.invalidate()
您可能应该使用Animation来实现您想要完成的事情