問題描述
帶有 9patch 的 LibGdx 標籤背景 (LibGdx label background with 9patch)
所以我遇到了這個我根本無法解決的問題。我正在 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() 時的大小,
參考解法
方法 1:
Call .pack()
on the label after .setText()
to tell it to size itself to its text (plus whatever padding there is in the background drawable). You don't need to call layout()
since that's handled automatically.
I'm not sure the exact reason you have to manually call pack()
, but this is generally the case with Widgets that you are not children of a WidgetGroup subclass (i.e. Table, VerticalGroup, etc.).
(by Alen Zarkovic、Tenfour04)