首页 > 解决方案 > 在 libGDX 中创建一个简单的按钮

问题描述

我是 libgdx 的新手,几个小时以来我一直在努力制作一个简单的按钮!首先我尝试以这种方式生成它(我在这个网站上找到):

public class TextButtonGenerator {

    public TextButton createButton(String label){
        BitmapFont font = new BitmapFont();
        TextureAtlas buttonAtlas = new TextureAtlas(Gdx.files.internal("sprite.txt"));
        Skin skin = new Skin(buttonAtlas);
//        skin.addRegions(buttonAtlas);
        TextButton.TextButtonStyle textButtonStyle = new TextButton.TextButtonStyle();
        textButtonStyle.font = font;
        textButtonStyle.up = skin.getDrawable("button");
        textButtonStyle.down = skin.getDrawable("button");
        textButtonStyle.checked = skin.getDrawable("button");
        return new TextButton(label, textButtonStyle);

我使用 Textpacker 在我的资产文件夹中创建 sprites.txt,但是,程序仍然没有运行,并且崩溃了。这是我收到的错误消息:

E/AndroidRuntime: FATAL EXCEPTION: GLThread 244475
    Process: com.mygdx.game, PID: 21525
    com.badlogic.gdx.utils.GdxRuntimeException: Error reading file: sprite.txt (Internal)E/AndroidRuntime: FATAL EXCEPTION: GLThread 244475
    Process: com.mygdx.game, PID: 21525
    com.badlogic.gdx.utils.GdxRuntimeException: Error reading file: sprite.txt (Internal)

它说我的代码中问题的根源是我构造 TextureAtlas 的地方。我认为问题可能是它应该是 .pack 文件而不是 .txt?但在本教程中,他们使用的是 txt 并且效果很好:

https://www.codeandweb.com/texturepacker/tutorials/libgdx-physics

我还发现了另一种生成不需要包的按钮的方法:

        Skin skin = new Skin();
        Pixmap pixmap = new Pixmap(1, 1, Pixmap.Format.RGBA8888);
        pixmap.setColor(Color.WHITE);
        pixmap.fill();
        skin.add("white", new Texture(pixmap));
        skin.add("default", new BitmapFont());

        TextButton.TextButtonStyle textButtonStyle = new TextButton.TextButtonStyle();
        textButtonStyle.up = skin.newDrawable("white", new Color(0, 0, 0, 1));
        textButtonStyle.font = skin.getFont("default");
        skin.add("default", textButtonStyle);
        return new TextButton(label, skin);

虽然这个没有崩溃但是没有按钮!当我运行它时,我只会在屏幕上看到我的背景颜色。坦率地说,我什至不理解上面发布的一半代码,我正在尝试学习我的引擎,但感觉就像我在 2 天内几乎没有取得任何进展。任何帮助将不胜感激。此外,我将按钮添加到我的舞台并在相应屏幕的渲染方法中调用 stage.draw()。

标签: javaandroidandroid-studiobuttonlibgdx

解决方案


推荐阅读