为移动设备缩放 libgdx UI?

Scale libgdx UI for mobile?

目前 desktop 版本的应用程序很好,按钮缩放得很好,但是当我部署到 android 时,它们很小,几乎无法使用。

DesktopLauncher ..

public class DesktopLauncher {
    public static void main (String[] arg) {
        LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
        config.title = "Color Catchin";
        config.width = 800;
        config.height = 480;
        new LwjglApplication(new ColorCatch(), config);
    }
}

AndroidLauncher ..

public class AndroidLauncher extends AndroidApplication {
    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
        config.useAccelerometer = false;
        config.useCompass = false;
        initialize(new ColorCatch(), config);
    }
}

Core代码..

public class MainMenu implements Screen {

    Skin skin = new Skin(Gdx.files.internal("ui/uiskin.json"));
    Stage stage = new Stage();

    final private ColorCatch game;

    public MainMenu(final ColorCatch gam) {

        game = gam;

        Gdx.input.setInputProcessor(stage);

        Table table = new Table();
        table.setFillParent(true);
        stage.addActor(table);

        final TextButton play = new TextButton("Play", skin);
        final TextButton quit = new TextButton("Quit", skin);
        table.add(play).pad(10);
        table.row();
        table.add(quit).pad(10);

        play.addListener(new ChangeListener() {
            public void changed(ChangeEvent event, Actor actor) {
                game.setScreen(new GameScreen(game));
                dispose();
            }
        });
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        stage.act(delta);
        stage.draw();
    }

    @Override
    public void resize(int width, int height) {
        stage.getViewport().update(width, height, true);
    }
}

桌面..

android ..

默认情况下 Stage 会将 ScalingViewport 设置为 Scaling.stretch,虚拟视口大小为 Gdx.graphics.getWidth() x Gdx.graphics.getHeight(参见 here).

在桌面上,您将从 800x480 的尺寸开始,因为这是您告诉启动器的尺寸。在 Android 上,这是动态的并且取决于设备。在您的设备上它可能是 1920x1080。

由于您没有更改按钮大小,因此它们在两种设备上的大小相同以像素为单位。由于屏幕密度完全不同,Android 上的按钮会显得小得多。

使两者达到相同水平的最简单解决方案是使用具有固定虚拟大小的 Viewport。例如new FitViewport(800, 480)。您可以通过 new Stage(viewport).

将该视口提供给舞台

但是,根据屏幕尺寸放大或缩小以保持纵横比和虚拟分辨率对于 UI 通常不是一个好主意。最好改用 ScreenViewport 并设置演员的相对尺寸。例如,您可以使用 Value.percentWidth(0.5f, rootTable) 将小部件的宽度设置为根 table 的 50%,即占据整个屏幕(通过 setFillParent(true))。