3

我正在测试 Libgdx 和 Scene2d。我希望这个小程序能显示一个标志,但它只画了一个黑屏。知道我错过了什么吗?

public class MyGame implements ApplicationListener {
    private Stage stage;

    @Override
    public void create() {
        stage = new Stage(800, 800, false);
        Gdx.input.setInputProcessor(stage);
        MyActor actor = new MyActor();
        stage.addActor(actor);
    }

    @Override
    public void render() {
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();
    }

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

    @Override
    public void resize(int width, int height) {
            stage.setViewport(800, 800, false);
    }
}


public class MyActor extends Actor {
    Sprite sprite;

    public MyActor() {
        sprite = new Sprite();
        sprite.setTexture(new Texture("data/libgdx.png"));

        setWidth(sprite.getWidth());
        setHeight(sprite.getHeight());
        setBounds(0, 0, getWidth(), getHeight());
        setTouchable(Touchable.enabled);
        setX(0);
        setY(0);
    }

    @Override
    public void draw(SpriteBatch batch, float parentAlpha) {
        Color color = getColor();
        batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
        batch.draw(sprite, getX(), getY());
    }
}
4

4 回答 4

11

使用纹理构造精灵并使用 Gdx.file.internal:

sprite = new Sprite(new Texture(Gdx.files.internal("data/libgdx.png")));

无论如何,如果您只想显示和操作图像,您可能更喜欢使用 Image 类:

    private Stage stage;
    private Texture texture;

    @Override
    public void create() {
        stage = new Stage();
        Gdx.input.setInputProcessor(stage);

        texture = new Texture(Gdx.files.internal("data/libgdx.png"));
        TextureRegion region = new TextureRegion(texture, 0, 0, 512, 275);          

        com.badlogic.gdx.scenes.scene2d.ui.Image actor = new com.badlogic.gdx.scenes.scene2d.ui.Image(region);
        stage.addActor(actor);
    }

    @Override
    public void render() {
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();
    }
于 2013-02-20T08:16:50.717 回答
3

Actor在我明确地将' 高度 ( setHeight(height)) 和宽度 ( setWidth(width)) 设置为Sprite' 值之前,我也遇到了黑屏。

于 2013-10-28T16:25:34.253 回答
0
tex = new Texture(Gdx.files.internal("happy.png"));
Image happy = new Image(tex);    
/* happy.setBounds(happy.getX(), happy.getY(), happy.getWidth(), happy.getHeight());  not needed if using full image               */    
stage.addActor(happy);
于 2016-05-15T16:46:58.330 回答
0

你的问题很可能是这条线,在draw方法中

batch.draw(sprite, getX(), getY());

我在绘制精灵时看到的代码是

sprite.draw(batch);
于 2018-10-22T08:39:31.607 回答