4

I want a certain ui element in my scene2d ui to scaledown on larger screens(not necessarily higher resolution screens). Its pretty straight forward in Android layout but how to get it working in libgdx. Maybe some API that I am missing ?

Can it be done through interface in Androidactivity? Current solution I can think of is declaring a flag in differend layout folders(values-sw600 etc) and fetch it in androidactivity in oncreate() and then pass it to libgdx through an interface. Please suggest if there is a better way

tej ethical
  • 163
  • 2
  • 10
  • Take a look at the Libgdx `Viewport`s, maybe you find something there. – Robert P Mar 25 '15 at 07:01
  • @Springrbua i am already using viewports but there seems to be nothing to target a large screen. Anyways i got it working flawlessly by declaring some boolean flags in xml for large screen and then fetch them in Game class through interfacr. – tej ethical Mar 25 '15 at 09:45

2 Answers2

2

If anyone is still curious on a easier method to solve this you can use the LibGDX method Gdx.graphics.getDensity();. This returns the pixel density of the screen and can be converted into an inches measurement. Calculation:

public float getScreenSizeInches () {
    //According to LibGDX documentation; getDensity() returns a scalar value for 160dpi.
    float dpi = 160 * Gdx.graphics.getDensity();
    float widthInches = Gdx.graphics.getWidth() / dpi;
    float heightInches = Gdx.graphics.getHeight() / dpi;

    //Use the pythagorean theorem to get the diagonal screen size
    return Math.sqrt(Math.pow(widthInches, 2) + Math.pow(heightInches, 2));
}

I haven't actually tested this but, in theory, it should work. Let me know if it doesn't.

vedi0boy
  • 1,030
  • 4
  • 11
  • 32
0

The solution presented by vedi0boy does not handle the PC platform correctly since Gdx.graphics.getWidth() does only return the size of the viewport, not the screen itself.

Here is a working solution for all platforms

public static double getScreenSizeInches()
{
    // Use the primary monitor as baseline
    // It would also be possible to get the monitor where the window is displayed
    Graphics.Monitor primary = Gdx.graphics.getPrimaryMonitor();
    Graphics.DisplayMode displayMode = Gdx.graphics.getDisplayMode(primary);

    float dpi = 160 * Gdx.graphics.getDensity();
    float widthInches = displayMode.width / dpi;
    float heightInches = displayMode.height / dpi;

    //Use the pythagorean theorem to get the diagonal screen size
    return Math.sqrt(Math.pow(widthInches, 2) + Math.pow(heightInches, 2));
}
davidgiga1993
  • 2,695
  • 18
  • 30
  • This doesn't work in mobile browser since Gdx.graphics.getDensity() isn't a valid value on the mobile browser platform. – Emperorlou Mar 14 '19 at 17:39
  • In case of browser applications you can use "Window.getClientWidth()" and "Window.getClientHeight()" inside your GWTApplication and pass that to the core application – davidgiga1993 Apr 23 '19 at 05:35