简体   繁体   中英

Android - Dynamic text on bitmap

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM