How to draw smooth text in libgdx?

前端 未结 10 1275
暖寄归人
暖寄归人 2020-12-01 00:01

I try to draw simple text in my android game on libgdx, but it\'s look sharp. How to make text look smooth in different resolutions? My Code:



        
10条回答
  •  一向
    一向 (楼主)
    2020-12-01 00:44

    In general you don't get sharp text because you are designing your game for a certain resolution and when you move to a different device, Libgdx scales everything to match the new resolution. Even with linear filtering scaling is bad on text because round corners are easily distorted. In a perfect world you would create the content dynamically at runtime according to the number of pixels available to you and not a single automatic scale would be used.

    This is the approach I'm using: Building everything for small screen (480 x 320), and when you open it on a bigger resolution, I load the BitmapFont with a higher size and apply and inverse scale to the one that Libgdx will later do automatically.

    Here's an example to make things clearer:

        public static float SCALE;
        public static final int VIRTUAL_WIDTH = 320;
        public static final int VIRTUAL_HEIGHT = 480;
    
    
        public void loadFont(){
    
         // how much bigger is the real device screen, compared to the defined viewport
         Screen.SCALE = 1.0f * Gdx.graphics.getWidth() / Screen.VIRTUAL_WIDTH ;
    
         // prevents unwanted downscale on devices with resolution SMALLER than 320x480
         if (Screen.SCALE<1)
            Screen.SCALE = 1;
    
         FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("data/Roboto-Regular.ttf"));
    
         // 12 is the size i want to give for the font on all devices
         // bigger font textures = better results
         labelFont = generator.generateFont((int) (12 * SCALE));
    
         // aplly the inverse scale of what Libgdx will do at runtime
         labelFont.setScale((float) (1.0 / SCALE));
         // the resulting font scale is: 1.0 / SCALE * SCALE = 1
    
         //Apply Linear filtering; best choice to keep everything looking sharp
         labelFont.getRegion().getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
    }
    

提交回复
热议问题