0

我试图在用户触摸屏幕时显示项目符号

我在这里做子弹

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有什么问题吗?谢谢

4

1 回答 1

1

在以下代码中:

Projectile p = new Projectile(TowerAnimation.this);
                    p.setProjectileDirection(x, y, 50);
                    projectiles.add(p);
                    Canvas c = null;    <------------------ here
                    p.onDraw(c);        <------------------ NPE

您正在设置并将其传递c给. 这就是您的:nullonDraw()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();
    }
于 2013-07-22T08:01:59.350 回答