我正在尝试将图像绘制到画布上,并且当程序成功编译并按照我的预期运行时,错误日志显示存在与下面的drawBitmap()方法关联的NullPointerException。奇怪的是,我的图像仍然被绘制在画布上。究竟是什么问题,我应该如何解决它?
我的代码:
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)
答案 0 :(得分: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);
一切都应该有效。