简体   繁体   English

使用Java和libgdx在android中调整文本大小

[英]Text sizing in android with java and libgdx

I'm creating text in libgx, but am having a problem where the text can be different sizes depending on the phone. 我正在libgx中创建文本,但是有一个问题,其中文本的大小可能取决于手机。 for the images, I resize them based on the screen size, but I can't do this with the text,b ecuase it needs wrapping and fitting to the phone. 对于图片,我会根据屏幕尺寸来调整它们的大小,但是我不能使用文本来做到这一点,因为它需要包装并适合手机。 Can anyone advise on a better way of drawing text that looks the same on any mobile screen. 任何人都可以建议一种更好的方式来绘制在任何移动屏幕上看起来都一样的文本。

The text class: 文字课:

public class TextActor extends Actor {
BitmapFont font;
String text;
float x = 0;
float y = 0;
float w = 10;
float h = 10;

public TextActor(String text){
    font = new BitmapFont(Gdx.files.internal("font.fnt"));
    this.text = text;
}

@Override
public void draw(SpriteBatch batch, float parentAlpha) {
    font.draw(batch, text, x, y);
}

public void setPosition(float x, float y) {
    this.x =x;
    this.y=y;
}

public void setText(String text){
    this.text = text;
}

} }

in the screen class: 在屏幕类中:

@Override
public void show() {
    batch = new SpriteBatch();
    stage = new Stage(Gdx.graphics.getWidth(),Gdx.graphics.getHeight(),true);
    scoreText = new TextActor("How to play: \n");
    scoreText.setPosition(10, ((Gdx.graphics.getHeight() /7) * 7));
    stage.addActor(scoreText);
}

Use TextBounds like: 使用类似TextBounds的方法:

textBounds = yourfont.getBounds("How to play: \\n"); textBounds = yourfont.getBounds(“播放方式:\\ n”); then get the width of textbounds like: textbounds.width. 然后获取textbounds的宽度,例如:textbounds.width。 then position where you want. 然后定位到您想要的位置。

In one of my project I used different font sizes for different phones like this: 在我的一个项目中,我为不同的手机使用了不同的字体大小,如下所示:

// create fonts
        float density = Gdx.graphics.getDensity();

        String path = "hdpi";
        if (density <= 1) {
            path = "mdpi";
        } else if (density > 1 && density < 1.5f) {
            path = "hdpi";
        } else if (density >= 1.5 && density < 2) {
            path = "xdpi";
        } else if (density >= 2) {
            path = "xxdpi";
        }

        normalFont = new BitmapFont(Gdx.files.internal("font/" + path + "/font.fnt"));

As you can see I used bitmapfont, you can find a bitmapfont creator here with you can create different size of bitmapfonts: http://www.badlogicgames.com/wordpress/?p=1247 . 如您所见,我使用了bitmapfont,可以在这里找到一个bitmapfont创建者,并可以创建不同大小的bitmapfonts: http : //www.badlogicgames.com/wordpress/ ?p = 1247。 This way you can work with the fonts like you worked with your resized bitmaps, and also you can resize the font like: 这样,您可以像处理调整后的位图一样使用字体,也可以调整字体的大小,例如:

normalFont.setScale(2.0f);

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM