0

我正在尝试在画布上绘制图像,当程序成功编译并按预期运行时,错误日志显示有一个 NullPointerException 与下面的 drawBitmap() 方法相关联。奇怪的是我的图像仍然被画在画布上。究竟是什么问题,我应该如何解决它?

我的代码:

public class ProgressBar extends View
{
    String packageName;

    public ProgressBar(Context context)
    {
        super(context);
        packageName = context.getPackageName();
    }

    public ProgressBar(Context context, AttributeSet attribs)
    {
        super(context, attribs);
        packageName = context.getPackageName();
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);

        int resourceId = getResources().getIdentifier("bar1", "drawable", packageName);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resourceId);
        canvas.drawBitmap(bitmap, 35, 35, null);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        // super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mWidth = View.MeasureSpec.getSize(widthMeasureSpec);
        mHeight = View.MeasureSpec.getSize(heightMeasureSpec);
        setMeasuredDimension(mWidth, mHeight);
    }
}

错误日志:

java.lang.NullPointerException
at android.graphics.Canvas.throwIfRecycled(Canvas.java:1057)
at android.graphics.Canvas.drawBitmap(Canvas.java:1097)
at com.myapp.ProgressBar.onDraw(ProgressBar.java:50)
at android.view.View.draw(View.java:13944)
at android.view.View.draw(View.java:13825)
at android.view.ViewGroup.drawChild(ViewGroup.java:3083)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2920)
at android.view.View.draw(View.java:13823)
at android.view.ViewGroup.drawChild(ViewGroup.java:3083)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2920)
at android.view.View.draw(View.java:13823)
at android.view.ViewGroup.drawChild(ViewGroup.java:3083)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2920)
at android.view.View.draw(View.java:13823)
at android.view.ViewGroup.drawChild(ViewGroup.java:3083)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2920)
at android.view.View.draw(View.java:13947)
at android.view.View.draw(View.java:13825)
at android.view.ViewGroup.drawChild(ViewGroup.java:3083)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2920)
at android.view.View.draw(View.java:13947)
4

1 回答 1

2

您永远不应该在 onDraw 中从资源中提取位图,因为 onDraw 每秒被调用多次,因此每次调用 onDraw 时它都没有时间解码该资源。

您应该在构造函数中解码位图,将其保存在类变量中并在 onDraw 中使用。

所以,基本上,你需要做的就是:

//add bitmap to class variable
private Bitmap bitmap;

//move these to constructor
int resourceId = getResources().getIdentifier("bar1", "drawable", packageName);
bitmap = BitmapFactory.decodeResource(getResources(), resourceId);

一切都应该工作。

于 2013-08-28T20:42:26.990 回答