Android drawBitmap绘画

时间:2013-07-22 07:52:40

标签: android canvas paint ondraw drawbitmap

我试图在用户触摸屏幕时显示子弹

我在这里制造子弹

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有什么不妥吗? 感谢

1 个答案:

答案 0 :(得分:1)

在以下代码中:

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();
    }