当用户触摸屏幕时,我正在尝试显示项目符号
我在这里制造子弹
public Projectile(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
paint = new Paint();
bulletBitmap = BitmapFactory.decodeResource(context.getResources(),
R.drawable.bullet);
}
public interface ProjectileListener {
public void onProjectileChanged(float delta, float angle);
}
public void setProjectileListener(ProjectileListener l) {
listener = l;
}
public void setProjectileDirection(int x, int y, int size){
pos = new Rect(x, y, size, size);
invalidate();
}
protected void onDraw(Canvas c) {
c.drawBitmap(bulletBitmap, pos, pos, paint);
super.onDraw(c);
}并在这里调用它
Projectile p = new Projectile(TowerAnimation.this);
p.setProjectileDirection(x, y, 50);
projectiles.add(p);
Canvas c = null;
p.onDraw(c);然而,我在这一行得到了错误
c.drawBitmap(bulletBitmap, pos, pos, paint);我的drawBitmap有什么问题吗?谢谢
发布于 2013-07-22 16:01:59
在以下代码中:
Projectile p = new Projectile(TowerAnimation.this);
p.setProjectileDirection(x, y, 50);
projectiles.add(p);
Canvas c = null; <------------------ here
p.onDraw(c); <------------------ NPE您正在将c设置为null并将其传递给onDraw()。这就是在你的onDraw()中发生的事情
protected void onDraw(Canvas c) {
null.drawBitmap(bulletBitmap, pos, pos, paint); <--------- NPE
super.onDraw(c);
}编辑1:
我不确定你想用你的代码做什么。检查类BulletsOnScreen。要使用它,您需要将其作为视图添加到某个布局中。例如,如果您有一个LinearLayout,则可以使用addView()方法:
myLinearLayout.addView(new BulletsOnScreen(this));
public class BulletsOnScreen extends View {
Bitmap bullet;
boolean touched;
float xValue, yValue;
public BulletsOnScreen(Context context) {
super(context);
setFocusable(true);
bullet = BitmapFactory.decodeResource(context.getResources(),
R.drawable.bullet);
touched = false;
}
protected void onDraw(Canvas canvas) {
if (touched) {
canvas.drawBitmap(bullet, xValue,
yValue, null);
touched = false;
}
}
public boolean onTouchEvent(MotionEvent event) {
xValue = event.getX();
yValue = event.getY();
touched = true;
invalidate();
}https://stackoverflow.com/questions/17782442
复制相似问题