所以我遇到了这个我根本无法解决的问题。 我正在 LibGdx 的帮助下制作游戏,并尝试创建聊天气泡功能。问题是,当我尝试将标签样式的背景更改为 9patch 可绘制时,它无法很好地缩放,或者根本无法缩放?
public class ChatBubble
{
private Label textLabel;
private BitmapFont font;
private Label.LabelStyle lStyle;
private int scaledWidth = 0;
private int scaledHeight = 0;
private Timer.Task currentTask;
private Texture bkg;
public ChatBubble()
{
font = new BitmapFont();
font.setColor(Color.BLACK);
bkg = new Texture("data/ui/chatb.9.png");
NinePatch np = new NinePatch(bkg,11,11,9,10);
NinePatchDrawable npd = new NinePatchDrawable(np);
lStyle = new Label.LabelStyle(font,font.getColor());
lStyle.background = npd;
textLabel = new Label("",lStyle);
textLabel.setVisible(false);
textLabel.setAlignment(Align.center);
currentTask = new Timer.Task() {
@Override
public void run() {
textLabel.setVisible(false);
}};
}
public void show(String text, float duration)
{
if(currentTask.isScheduled())currentTask.cancel();
textLabel.setText(text);
textLabel.setVisible(true);
scaledHeight = (int)textLabel.getPrefHeight();
scaledWidth = (int)textLabel.getWidth()/2;
Timer.schedule(currentTask,duration);
}
public void show(String text)
{
if(currentTask.isScheduled())currentTask.cancel();
textLabel.setText(text);
textLabel.setVisible(true);
scaledHeight = (int)textLabel.getPrefHeight();
scaledWidth = (int)textLabel.getWidth()/2;
Timer.schedule(currentTask,(float)(text.length()*0.1));
}
public void draw(SpriteBatch batch, float x, float y)
{
if(!textLabel.isVisible())return;
textLabel.setPosition(x - scaledWidth, y + scaledHeight);
batch.begin();
textLabel.draw(batch, 1);
batch.end();
}
}
游戏中的外观:
9batch 的外观:
如有任何帮助,我们将不胜感激!
更新: 我发现我的 9patch 缩放正常,问题在于调用 setText() 时标签没有更新其大小,因此宽度和高度为 0,因为构造函数是“”..在标签上调用 layout() 也不能解决此问题。
最佳答案
在.setText()
之后调用标签上的.pack()
,告诉它根据文本调整自身大小(加上背景可绘制中的任何填充)。您无需调用 layout()
,因为这是自动处理的。
我不确定您必须手动调用 pack()
的确切原因,但这通常是 Widget 的情况,您不是 WidgetGroup 子类(即 Table、VerticalGroup 等)的子类。
关于java - 带有 9patch 的 LibGdx 标签背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36503349/