2015-11-06 83 views
-2

時NullPointeerException朝着這條線NullPointerException異常試圖加載圖像

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); 
} 

因爲文件存儲在該項目應該不爲空指出。我可以看到問題出在哪裏的唯一方法是因爲我從複製的初始框架將所有圖片保存在一個名爲assets的獨立文件夾中,該文件夾顯然不是默認文件夾。相反,我將所有資源放在可繪製文件夾中。究竟是什麼問題?

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) 
+0

Plaese,顯示更多代碼並打印logcat –

+0

如果在代碼中從一行中拋出NPE,您可以嘗試在該行上設置斷點以查看哪些內容爲null,然後從那裏回溯。我猜可能在這裏畫布 - 但正如亞瑟所說,我們確實需要看到更多的代碼。 –

+0

@ArthurKorchagin我增加了更多的代碼。這是更多的空白點,但我想我可以解決其餘的,如果我認爲主要指出。 –

回答

1

Assets是圖像的默認文件夾,如果你嘗試將其加載爲bitmapDrawable文件夾包含您要使用的圖像R.drawable.xxx

+0

我在哪裏可以找到資產文件夾?我使用android studio嗎?編輯:我找到了。 –

相關問題