尝试加载图像时出现NullPointerException

时间:2015-11-06 15:17:38

标签: android

NullPointeerException指向此行

    import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;

public class Painter {
    private Canvas canvas;
    private Paint paint;
    private Rect srcRect;
    private Rect dstRect;
    private RectF dstRectF;

public Painter(Canvas canvas) {
    this.canvas = canvas;
    paint = new Paint();
    srcRect = new Rect();
    dstRect = new Rect();
    dstRectF = new RectF();
}

public void setColor(int color) {
    paint.setColor(color);
}

public void setFont(Typeface typeface, float textSize) {
    paint.setTypeface(typeface);
    paint.setTextSize(textSize);
}

public void drawString(String str, int x, int y) {
    canvas.drawText(str, x, y, paint);
}

public void fillRect(int x, int y, int width, int height) {
    dstRect.set(x, y, x + width, y + height);
    paint.setStyle(Paint.Style.FILL);
    canvas.drawRect(dstRect, paint);
}

public void drawImage(Bitmap bitmap, int x, int y) {
// NullPointerException here        canvas.drawBitmap(bitmap, x, y, paint);
}

public void drawImage(Bitmap bitmap, int x, int y, int width, int height) {
    srcRect.set(0, 0, bitmap.getWidth(), bitmap.getHeight());
    dstRect.set(x, y, x + width, y + height);
    canvas.drawBitmap(bitmap, srcRect, dstRect, paint);
}

public void fillOval(int x, int y, int width, int height) {
    paint.setStyle(Paint.Style.FILL);
    dstRectF.set(x, y, x + width, y + height);
    canvas.drawOval(dstRectF, paint);
}

由于文件存储在项目中,因此不应为null。我能看到问题所在的唯一方法是因为我复制的初始框架将所有图片保存在一个名为assets的单独文件夹中,这显然不是默认文件夹。相反,我将所有资源放在drawable文件夹中。究竟是什么问题?

Logcat
11-06 10:21:55.114  25146-25168/rect.draw.gametest E/AndroidRuntime﹕ FATAL EXCEPTION: Game Thread

 Process: rect.draw.gametest, PID: 25146
    java.lang.NullPointerException
            at android.graphics.Canvas.throwIfCannotDraw(Canvas.java:1083)
            at android.graphics.Canvas.drawBitmap(Canvas.java:1139)
            at rect.draw.gametest.model.util.Painter.drawImage(Painter.java:45)
            at rect.draw.gametest.model.state.MenuState.render(MenuState.java:28)
            at rect.draw.gametest.GameView.updateAndRender(GameView.java:100)
            at rect.draw.gametest.GameView.run(GameView.java:119)
            at java.lang.Thread.run(Thread.java:841)

1 个答案:

答案 0 :(得分:1)

否。Assets是图片的默认文件夹,如果您尝试将其加载为bitmapDrawable文件夹包含您要R.drawable.xxx使用的图片。< / p>