使用默认Arial-15打印文本

时间:2014-03-09 02:25:56

标签: android libgdx

我正在尝试打印一条短信,看起来我正在做的一切都没有显示任何错误,但它不会打印“ Hello World ”。有谁知道我可能做错了什么?我四处寻找,我找不到解决方案。我知道你可以使用自定义字体并将它们放在你的资产文件夹中,但我被告知你不需要这样做,默认是Arial-15。

以下是我得到的图片:http://i.imgur.com/wHPa3AV.png

package com.me.mygdxgame;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class MyGdxGame implements ApplicationListener {
    private OrthographicCamera camera;
    private SpriteBatch batch;
    private BitmapFont font;
    private float x, y;

    private String str;

    @Override
    public void create() {      
        float w = Gdx.graphics.getWidth();
        float h = Gdx.graphics.getHeight();

        str = "Hello World!";
        font = new BitmapFont();

        camera = new OrthographicCamera(1, h/w);
        batch = new SpriteBatch();
    }

    @Override
    public void dispose() {
        batch.dispose();
    }

    @Override
    public void render() {      
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

        x = Gdx.graphics.getWidth();
        y = Gdx.graphics.getHeight();

        batch.setProjectionMatrix(camera.combined);
        batch.begin();
        font.setColor(Color.RED);
        font.draw(batch, str, x/2, y/2);
        batch.end();
    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }
}

1 个答案:

答案 0 :(得分:1)

再次查看您的代码。我用评论标记了重要的行

@Override
public void create() {      
    float w = Gdx.graphics.getWidth();
    float h = Gdx.graphics.getHeight();

    str = "Hello World!";
    font = new BitmapFont();

    // Here you are setting your viewport to width = 1, height = 0.75 for example
    camera = new OrthographicCamera(1, h/w);
    batch = new SpriteBatch();
}

@Override
public void dispose() {
    batch.dispose();
}

@Override
public void render() {      
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

    x = Gdx.graphics.getWidth();
    y = Gdx.graphics.getHeight();

    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    font.setColor(Color.RED);
    // for a screen resolution of 800x600 you are now telling the font to draw the text at 400, 300.
    font.draw(batch, str, x/2, y/2);
    batch.end();
}

你基本上只是使用错误的坐标。如果您将文本呈现在正确的位置,则文本将可见。尝试font.draw(batch, str, 0.5f, 0.5f);camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());