首页 > 解决方案 > 平铺背景上的 LibGDX 9 补丁图像

问题描述

我正在使用 LibGDX UI 组件来显示我的游戏的 UI。

我想在我的菜单后面显示一个带框的大理石背景。为此,我有一个带有框架的九个补丁图像和一个大理石背景图像

它试图在我的菜单中使用两者,由一个包含表格的 ScrollPane 组成。

所以我将 9 个补丁帧定义为 ScrollPane 背景:

com.badlogic.gdx.scenes.scene2d.ui.ScrollPane$ScrollPaneStyle: {
    default: { ..., background: frame }
}

并将(大)大理石背景添加到我的桌子上:

table.setBackground(skin.getTiledDrawable("big-marble-texture"));

然而,它看起来像框架围绕大理石背景,而不是它的一部分:

在此处输入图像描述

我不能只将大理石纹理作为 9 补丁的一部分:我希望它是平铺的,而不是缩放到菜单尺寸(我试过了,它看起来很糟糕)。我还尝试直接在菜单顶部的舞台中显示框架,它可以工作,但是代码使用起来真的很痛苦,尤其是使用动态 UI,如工具提示或移动卡片。

在 libgdx UI 组件中执行此操作的推荐方法是什么?

标签: javalibgdx

解决方案


我不确定解决此问题的推荐方法是什么,但一种方法是创建一个由 aTiledDrawable和a 组合而成的类,NinePatch并让该类扩展BaseDrawable

这样,您可以覆盖该draw方法以首先将背景绘制为 a TiledDrawable(偏移以考虑 的插入NinePatch),然后将 绘制NinePatch为边框。

例如:

package com.bornander.sandbox;

import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.NinePatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.utils.BaseDrawable;
import com.badlogic.gdx.scenes.scene2d.utils.TiledDrawable;
import com.badlogic.gdx.scenes.scene2d.utils.TransformDrawable;

public class BorderedTiledDrawable extends BaseDrawable implements TransformDrawable {
    private TiledDrawable region;
    private NinePatch patch;
    private int left;
    private int top;
    private int right;
    private int bottom;

    public BorderedTiledDrawable(Texture background, Texture border, int left, int top, int right, int bottom) {
        region = new TiledDrawable(new TextureRegion(background));
        this.patch = new NinePatch(border, left, top, right, bottom);
        this.left = left - 1;
        this.top = top - 1;
        this.right = right - 1;
        this.bottom = bottom - 1;
        setMinWidth(patch.getTotalWidth());
        setMinHeight(patch.getTotalHeight());
        setTopHeight(patch.getPadTop());
        setRightWidth(patch.getPadRight());
        setBottomHeight(patch.getPadBottom());
        setLeftWidth(patch.getPadLeft());
    }

    @Override
    public void draw(Batch batch, float x, float y, float originX, float originY, float width, float height, float scaleX, float scaleY, float rotation) {
        region.draw(batch, x, y, originX, originY, width, height, scaleX, scaleY, rotation);
        patch.draw(batch, x, y, originX, originY, width, height, scaleX, scaleY, rotation);
    }

    @Override
    public void draw(Batch batch, float x, float y, float width, float height) {
        region.draw(batch, x + left, y + top, width - (left + right), height - (top + bottom));
        patch.draw(batch, x, y, width, height);
    }
}

看起来像这样:

平铺和九个补丁

如果你的九个补丁有非常圆的角,它就不能完全工作,但这也很容易调整。


推荐阅读