Skip to content

Instantly share code, notes, and snippets.

@chandruscm
Created November 3, 2016 13:16
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save chandruscm/afa688262f22714eabfc1d64d389e657 to your computer and use it in GitHub Desktop.
How to manage and scale graphic assets across different screen resolutions in LibGDx, as implemented in Orble https://play.google.com/store/apps/details?id=com.chandruscm.orble.android
/*
3 set of assets are used for targeting 480p, 720p and 1080p+ resolutions
These are packed in TextureAtlases placed in folders SD/, MD/, LD/ respectively inside res/
Each containing the TextureAtlas with the name gameScreen.pack
*/
public static float dpiScale;
public static String dpiPixel;
//Check if the dpiScale has been calculated, if not find it and save it to preference(only for the first run)
if(preferences.contains("dpiScale") && preferences.contains("dpiPixel"))
{
dpiScale = preferences.getFloat("dpiScale");
dpiPixel = preferences.getString("dpiPixel");
}
else
setDpi();
//Initial choice is based on the screenWidth
private void setDpi()
{
int screenWidth = Gdx.graphics.getWidth();
int screenHeight = Gdx.graphics.getHeight();
//Taking minimum gives the most appropriate scaling factor.
if(screenWidth < 720)
{
dpiScale = Math.min(screenWidth/480f, screenHeight/854f);
dpiPixel = "SD";
}
else if(screenWidth < 1080)
{
dpiScale = Math.min(screenWidth/720f, screenHeight/1280f);
dpiPixel = "MD";
}
else
{
dpiScale = Math.min(screenWidth/1080f, screenHeight/1920f);
dpiPixel = "LD";
}
preferences.putFloat("dpiScale", dpiScale);
preferences.putString("dpiPixel", dpiPixel);
preferences.flush();
}
//Load the correct TextureAtlas in AssetManager
getAssetManager().load("res/" + dpiPixel + "/gameScreen.pack", TextureAtlas.class);
//Scaling the sprites
private Sprite setScaledSprite(TextureRegion textureRegion)
{
Sprite sprite = new Sprite(textureRegion);
sprite.setSize(sprite.getWidth() * dpiScale, sprite.getHeight() * dpiScale);
sprite.setOriginCenter();
return sprite;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment