正在学习android sprite,但我的位图出现错误
我正在学习如何在android上制作精灵 我的位图有问题正在学习android sprite,但我的位图出现错误,android,bitmap,nullpointerexception,Android,Bitmap,Nullpointerexception,我正在学习如何在android上制作精灵 我的位图有问题 public class Sprite { Bitmap b; BoardGame bg; int x,y; int xSpeed,ySpeed; int height,width; int direction; public Sprite(BoardGame BoardGame, Bitmap blob) { b = blob; bg = BoardGame; height = b.getHeight();
public class Sprite {
Bitmap b;
BoardGame bg;
int x,y;
int xSpeed,ySpeed;
int height,width;
int direction;
public Sprite(BoardGame BoardGame, Bitmap blob) {
b = blob;
bg = BoardGame;
height = b.getHeight();
width = b.getWidth();
x = 0;
y = 0;
xSpeed = 5;
ySpeed = 0;
direction = 0;
}
private void update()
{
if (x > bg.getWidth() - width - xSpeed)
{
xSpeed = 0;
ySpeed = 5;
direction = 1;
}
if (y > bg.getHeight() - height - xSpeed) {
xSpeed = -5;
ySpeed = 0;
direction = 2;
}
if (x + xSpeed < 0)
{
x = 0;
xSpeed = 5;
ySpeed = 0;
direction = 3;
}
x+=xSpeed;
y+=ySpeed;
}
public void onDraw(Canvas canvas) {
update();
Rect src = new Rect(0,0,width,height);
Rect dst = new Rect(x,y,x+width,y+height);
canvas.drawBitmap(b,x,y,null);
}
}
由于某种原因,“getHeight()”不起作用
传递给Sprite
构造函数的参数Bitmap blob
为null。您尝试取消对空对象的引用
首先创建Sprite
,然后再创建blob
。这是在创建BoardGame
时,在这里初始化Sprite
,blob
为空
BoardGame BoardGame = new BoardGame(this);//here you create it, but blob is null!
//first here you initialize blob
blob = BitmapFactory.decodeResource(getResources(),R.drawable.monkey);
blob = Bitmap.createScaledBitmap(ball,170,170,false);
一个可能的解决方案是调整main活动的onCreate
方法中的执行顺序:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ball = BitmapFactory.decodeResource(getResources(), R.drawable.aqua_ball_green);
ball = Bitmap.createScaledBitmap(ball,170,170,false);
blob = BitmapFactory.decodeResource(getResources(),R.drawable.monkey);
blob = Bitmap.createScaledBitmap(ball,170,170,false);
//Put BoardGame here:
BoardGame BoardGame = new BoardGame(this);
setContentView(BoardGame);
}
这样,当blob
也已初始化时,您就可以初始化BoardGame
希望这能澄清问题 您能否发布您的main活动
代码,在那里您可以创建Sprite
,并且位图
也是如此?@user8完成,这是唯一的活动。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ball = BitmapFactory.decodeResource(getResources(), R.drawable.aqua_ball_green);
ball = Bitmap.createScaledBitmap(ball,170,170,false);
blob = BitmapFactory.decodeResource(getResources(),R.drawable.monkey);
blob = Bitmap.createScaledBitmap(ball,170,170,false);
//Put BoardGame here:
BoardGame BoardGame = new BoardGame(this);
setContentView(BoardGame);
}