我是Android图形的新手,就像自定义视图等。我有以下程序,但SurfaceView由于某种原因不会从另一个类的对象中绘制图像。我继续得到一个空指针异常。
主要课程:
public class Main extends Activity {
MyView view;
TestObject test;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
view = new MyView(this, this);
test = new TestObject(this);
setContentView(view);
}
public TestObject getTest() {
return test;
}
public void setTest(TestObject test) {
this.test = test;
}
}
查看课程:
public class MyView extends SurfaceView implements Runnable {
SurfaceHolder surfaceHolder;
Thread thread;
TestObject test;
public MyView(Context context, Main main) {
super(context);
this.test = main.getTest();
surfaceHolder = getHolder();
thread = new Thread(this);
thread.start();
}
@Override
public void run() {
while(true){
if(!surfaceHolder.getSurface().isValid())
continue;
Canvas canvas = surfaceHolder.lockCanvas();
canvas.drawBitmap(test.getImage(), test.getX(), test.getY(), null);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
对象类:
public class TestObject {
Main main;
Bitmap image;
int x,y;
DisplayMetrics dm;
public TestObject(Main main) {
this.main = main;
image = BitmapFactory.decodeResource(main.getResources(), R.drawable.ic_launcher);
dm = new DisplayMetrics();
x = dm.widthPixels / 2;
y = dm.heightPixels / 2;
}
public Bitmap getImage() {
return image;
}
public void setImage(Bitmap image) {
this.image = image;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
我在MyView类的canvas.drawBitmap(test.getImage(), test.getX(), test.getY(), null);
得到一个空指针异常。扼杀,如果要说canvas.drawBitmap(BitmapFactory.decodeResource(main.getResources(), R.drawable.ic_launcher), 0, 0, null);
(或任何其他x,y位置),它将起作用。
任何帮助表示赞赏!
答案 0 :(得分:0)
你应该覆盖" onDraw"方法" MyView"而不是实现Runnable。