繁体   English   中英

如何在libgdx中的按钮上添加绘图功能?

[英]How can add a drawing function to a button in libgdx?

我正在使用Screen-2D构建按钮。 我想给按钮一个功能,当它被单击时,将绘制一个精灵,我该怎么做。 这不仅是我的全部代码,还足以说明所讨论的内容。

public void create () {
    buttonStyle = new TextButtonStyle();
    buttonStyle.up = skin.getDrawable("button");
    buttonStyle.over = skin.getDrawable("buttonpressed");
    buttonStyle.down = skin.getDrawable("buttonpressed");
    buttonStyle.font = font;
    button = new TextButton("START", buttonStyle);

    stage.addActor(button);
    Gdx.input.setInputProcessor(stage);
    button.addListener(new InputListener() {    
        @Override
        public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
            drawTile(200,50);
            return true;
        }
    });
}

// method used to draw a sprite when passing certain coordinates 
public void drawTile(int x , int y) {    
    spriteBatch.draw(sprite, x  , y   );
}

public void render () {
    Gdx.gl.glClearColor(1f, 0f, 0f, 1f);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    camera.update();
    spriteBatch.begin();
    spriteBatch.draw(background, 0, 0);
    drawGrid();
    spriteBatch.draw(startButton, 0, 0);
    stage.draw();
    spriteBatch.end()
}

你有正确的主意。 请参阅以下示例:

button.addListener(new ChangeListener() {
    @Override
    public void changed (ChangeEvent event, Actor actor) {
        drawTile(200,50);
    }
}); 

https://github.com/libgdx/libgdx/wiki/Scene2d.ui#changeevents

我认为您需要阅读更多有关LibGDX和Scene2D如何工作的教程:事件处理是在渲染方法之前完成的,因此清除屏幕时,所有绘图都将被删除。

正确的方法是在单击时将精灵(作为Drawable)添加到小部件组。 然后,舞台渲染将渲染所有组件,包括精灵。

与MVC模式相比:阶段是您的模型,您可以在事件发生时修改模型,而render方法是模型的视图(绘制模型)。

暂无
暂无

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

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