I'm currently trying to show a score which requires the text to change dynamically in a game. I've searched around and found that most cases people use XML layout for the text. My problem is I don't use XML at all for the game because everything are bitmap graphics. Any tips or suggestion for my situation?

Here is the draw method to draw everything

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
}

Here is the method to update the score

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

It returns NullPointerException at android.graphics.Canvas.drawText(Native Method). I tried logging the "scoreString" and it shows correctly.

Edit: Solved, NullPointerException caused by null paint object. Simply create paint object Paint paintObj = new Paint(); and set the object paintObj.setTextSize(textSize) and paintObj.setColor(Color.WHITE);

有帮助吗?

解决方案

If you are doing your drawing directly through a View or SurfaceView object, you may want to check the Canvas documentation:

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

Specifically the draw text function. This is what I use.

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

Enjoy!

If you're using an Open GL Surface, I'm not sure what APIs are available. On other platforms I've uploaded my characters as a texture atlas and just placed the textures for the correct text that I wanted on the scene.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top