2012-01-03 32 views
0

我正在嘗試顯示需要文本在遊戲中動態更改的分數。 我周圍搜索,發現大多數情況下人們使用XML佈局的文本。 我的問題是我根本不使用XML,因爲一切都是位圖圖形。 對我的情況有任何提示或建議?Android - 位圖上的動態文本

這裏是繪製方法來繪製一切

public void render(Canvas canvas){ 
    Bitmap bitmap; 
    Graphics.Coordinate coords; 
    canvas.drawBitmap(bgBitmap, 0, 0, null); 
    canvas.drawBitmap(closeBtnBitmap, 700, 0, null); 
    canvas.drawBitmap(groundBitmap, 0, 315, null); 
    canvas.drawBitmap(petBitmap, petX, petY, null); 
    for(Graphics pics : coins){ 
     bitmap = pics.getBitmap(); 
     coords = pics.getCoord(); 
     canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null); 
    } 
    canvas.drawBitmap(scoreBitmap, 300, 20, null); 
    canvas.drawText(scoreString, 300, 20, null); //change null to paintObj 
} 

下面是更新得分

private void updateScore(int score){ 
    initScore += score; 
    totalScore = initScore; 
    scoreString = Integer.toString(totalScore); 
} 

它在android.graphics.Canvas.drawText(本機方法)返回NullPointerException異常的方法。我試着記錄「scoreString」,它顯示正確。

編輯:已解決,由null繪製對象引起的NullPointerException。只需創建噴漆的對象Paint paintObj = new Paint();和設置對象paintObj.setTextSize(textSize)paintObj.setColor(Color.WHITE);

+0

您可以使用畫布來顯示文本:Paint p = new Paint(); p.setColor(Color.BLUE); canvas.drawText(「your string」,10,10,p); – 2012-01-03 06:20:26

+0

@HirenDabhi使用該解決方案,但返回錯誤。我已經添加了我的代碼。你的代碼中的 – 2012-01-03 07:14:27

+0

你在drawText(最後一個參數)中傳遞null。傳遞新的Paint(); – 2012-01-03 07:24:05

回答

2

如果您通過查看或SurfaceView對象直接做您的繪圖,您可能要檢查畫布文檔:

http://developer.android.com/reference/android/graphics/Canvas.html

具體的繪製文字功能。這是我使用的。

http://developer.android.com/reference/android/graphics/Canvas.html#drawText(java.lang.String,浮球,浮球,android.graphics.Paint)

享受!

如果您使用Open GL Surface,我不確定哪些API可用。在其他平臺上,我將角色上傳爲紋理地圖集,並在場景中放置了我想要的正確文本的紋理。

+0

我實際上找到了這樣的東西http://stackoverflow.com/questions/6304195/android-displaying-score-as-a-string-on-canvas-is-創建一個新的字符串每dr 但我無法讓它與錯誤NullPointerException異常工作,我完全按照它順便說一句。如果這就是你所說的解決方案,我會嘗試着解決它。 – 2012-01-03 06:10:15

+0

該設置是否適合您,或者您在尋找不同的解決方案?如果是後者,請詳細解釋您如何開發遊戲,並提供更好的解決方案。 – nmjohn 2012-01-03 06:11:43

+0

如果你想發佈你的示例代碼,我可以幫助調試它。我的猜測是,無論是畫布對象無效還是畫圖對象都無效,我可以嘗試在這個問題或其他鏈接中調試它。 – nmjohn 2012-01-03 06:21:39