如何在libgdx中绘制流畅的文本?

Jus*_*Man 33 libgdx

我尝试在我的Android游戏中在libgdx上绘制简单文本,但它看起来很清晰.如何使文本在不同的分辨率下看起来流畅?我的代码:

private BitmapFont font;

font = new BitmapFont();

font.scale((ppuX*0.02f));

font.draw(spb, "Score:", width/2-ppuX*2f, height-0.5f*ppuY);
Run Code Online (Sandbox Code Playgroud)

小智 51

font.getRegion().getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
Run Code Online (Sandbox Code Playgroud)

这将获得BitmapFont中使用的纹理并将其过滤更改为双线性,从而允许更高的结果图像质量,同时以略微更慢(差异通常不明显)GPU渲染的成本进行上下缩小.

  • 请加一些解释. (20认同)
  • 他已将线性纹理过滤应用于字体纹理.似乎在某些设备上有意义 - 在我的情况下是Nexus 7(1代),这个解决方案帮助了我. (2认同)

Rod*_*yde 28

一个解决方案是使用FreeType的扩展libgdx,描述在这里.这允许您从.ttf字体动态生成位图字体.通常,一旦知道目标分辨率,就会在启动时执行此操作.

这是一个例子:

int viewportHeight;
BitmapFont titleFont;
BitmapFont textFont;

private void createFonts() {
    FileHandle fontFile = Gdx.files.internal("data/Roboto-Bold.ttf");
    FreeTypeFontGenerator generator = new FreeTypeFontGenerator(fontFile);
    FreeTypeFontParameter parameter = new FreeTypeFontParameter();
    parameter.size = 12;
    textFont = generator.generateFont(parameter);
    parameter.size = 24;
    titleFont = generator.generateFont(parameter);
    generator.dispose();
}
Run Code Online (Sandbox Code Playgroud)


The*_*ama 22

您应该快速查看自定义字体着色器和/或DistanceField-Fonts.它们易于理解,同样易于实现:

https://github.com/libgdx/libgdx/wiki/Distance-field-fonts

DistanceFieldFonts保持平滑,即使你高档它们:

在此输入图像描述

  • 不完全正确.您可以在着色器中为字体着色.您可能想说,您一次只能使用一种颜色.但即便如此,也可以使用更复杂的着色器或其他纹理来克服. (8认同)
  • 请记住,这仅适用于灰度字体,没有颜色. (4认同)

小智 12


she*_*tan 6

一般情况下,由于您正在设计游戏以获得特定分辨率,并且当您移动到其他设备时,Libgdx会缩放所有内容以匹配新分辨率.即使使用线性滤波,缩放在文本上也很糟糕,因为圆角很容易失真.在完美的世界中,您可以根据可用的像素数在运行时动态创建内容,而不会使用单个自动缩放.

这就是我正在使用的方法:为小屏幕(480 x 320)构建所有内容,当你以更大的分辨率打开它时,我加载BitmapFont更大的尺寸,然后应用并反向缩放到Libgdx稍后的那个自动做.

这是一个让事情更清晰的例子:

    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);
}
Run Code Online (Sandbox Code Playgroud)