首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >安卓drawBitmap paint

安卓drawBitmap paint
EN

Stack Overflow用户
提问于 2013-07-22 15:52:40
回答 1查看 5.1K关注 0票数 0

当用户触摸屏幕时,我正在尝试显示项目符号

我在这里制造子弹

代码语言:javascript
复制
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);
    }

并在这里调用它

代码语言:javascript
复制
Projectile p = new Projectile(TowerAnimation.this);
                        p.setProjectileDirection(x, y, 50);
                        projectiles.add(p);
                        Canvas c = null;
                        p.onDraw(c);

然而,我在这一行得到了错误

代码语言:javascript
复制
c.drawBitmap(bulletBitmap, pos, pos, paint);

我的drawBitmap有什么问题吗?谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-22 16:01:59

在以下代码中:

代码语言:javascript
复制
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()中发生的事情

代码语言:javascript
复制
protected void onDraw(Canvas c) {
    null.drawBitmap(bulletBitmap, pos, pos, paint);    <--------- NPE
    super.onDraw(c);
}

编辑1:

我不确定你想用你的代码做什么。检查类BulletsOnScreen。要使用它,您需要将其作为视图添加到某个布局中。例如,如果您有一个LinearLayout,则可以使用addView()方法:

代码语言:javascript
复制
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();
    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17782442

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档