Search code examples
androidopengl-eslibgdx

Set same height for icons and text in Libgdx


I want to draw a score bar like shown below. Score text length varies as score is accumulated. The bar size should be 0.075*screen height.

1) How do I set height for start texture and fonts with respect to score bar height. This should work in all screen sizes.

2) Also how do I draw a orange rectangle, where it width varies based on score length in libgdx.

enter image description here

My code is shows below.

public class ScoreBar {

    float totalTime = 0;
    long totalScore = 0;
    float scoreLen = 10;
    float scoreHeight = 10;
    String timeString = "0:00";
    String scoreString = "0";
    int hours =0;
    int minutes =0;
    int seconds =0;

    float width;
    float height;
    BitmapFont font;
    float top = 0;
    float tmargin = 10;
    float hmargin = 20;
    Texture starIcon;
    Texture clockIcon;
    float barHeight  =10;
    float iconSize = 10;

    public ScoreBar(BitmapFont scoreFont, float width, float height, Texture star, Texture clock){
        this.width = width;
        this.height = height;
        this.font = scoreFont;
        font.setColor(1, 0, 0, 1);

        barHeight = height * .075f;
        tmargin = barHeight * 0.2f;
        hmargin = barHeight * 0.5f;
        iconSize = barHeight - 2*tmargin;
        top = height - tmargin/2;
        starIcon = star;
        clockIcon = clock;
    }

    public void render(SpriteBatch batch){
        batch.draw(starIcon, hmargin, top - iconSize, iconSize, iconSize);
        batch.draw(clockIcon, width*0.65f, top - iconSize,  iconSize, iconSize);
        font.draw(batch, scoreString, hmargin + iconSize + tmargin, top - scoreHeight);
        font.draw(batch, timeString, width*0.65f + tmargin + iconSize, top - scoreHeight);
    }

Solution

  • Use the ShapeRenderer to draw your orange rectangle. Here's a link to the documentation. They put in sample code there so I won't reiterate over that again. If you want it's width to vary over the score you can code some simple updating of the rectangle width.

    if(score > 100){
        rectWidth = 25;
    } elif (score > 200){
        rectWidth = 35;
    }
    

    For your icon use a simple SpriteBatch to draw your icon over the orange rectangle.

    For all this font height business, experiment with the fonts and find one that covers the height of the icon well and then adjust the width of the rectangle accordingly.

    If this doesn't work you could create your own font, scale something etc.

    The height of these textures shouldn't change at run-time so just experiment before and find something that works!

    I hope this answer helped you! If you have any further questions please feel free to comment below!