我正在尝试在画布上绘制图像,当程序成功编译并按预期运行时,错误日志显示有一个 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)