javaandroidlibgdxresolutionresolution-independence

How to position text correctly in LibGDX?


Currently I am using the following calculation to calculate the font scale resolution independent:

fontScale = ( Gdx.graphics.getDensity() / BaseDensity ) * (( (float)Gdx.graphics.getWidth() / (float)BaseResolutionWidth ) / (Gdx.graphics.getDensity() / BaseDensity) );

And I am using the following code to position my fonts relatively to one another:

font.draw(batch, glyphLayout, UniX(0.5f) - w * 0.5f, UniY(0.23f + 0.04f * scale) - h * 0.5f);

I am totally confused. The texts get displayed inside of each other on my 8 inch tablet, but they are alligned perfectly correct on my phone.

How should I correctly position this resolution independent?


Solution

  • Since I am using my App strictly in portrait mode, I am using the following aspect ratio. This seems to work flawlessly cross my devices (phones & tablets).

    aspectRatio = ( Gdx.graphics.getHeight() / Gdx.graphics.getWidth() );
    fontScale = ( ( Gdx.graphics.getDensity() / BaseDensity ) * aspectRatio );