LibGDX - ImageButton - 如何设置背景图像

4

据我所知,在LibGDX中,ImageButton是包含图像的框架。是否可以设置框架的背景?

例如,我想使用按钮背景,并在该图像顶部应用图标。

当前代码

带有背景的皮肤:

"com.badlogic.gdx.scenes.scene2d.ui.ImageButton$ImageButtonStyle": {
    "default": {
        "imageDown": "button-down", 
        "imageUp": "button-up"
    }
}

创建ImageButton:

// Getting imageButtonStyle with "default" style, as it just has the background.
ImageButton.ImageButtonStyle imageButtonStyle = skin.get( "default", ImageButton.ImageButtonStyle.class );
ImageButton button = new ImageButton( imageButtonStyle );
// Set the image on the button to something.

背景图片。

静态背景按钮图像

带有叠加图标的背景图片。

带有心形图标的静态背景按钮图像 带有邮件图标的静态背景按钮图像

感谢您的帮助。

3个回答

11

诀窍在于使用两种不同的样式。ImageButtonStyle用于设置图标属性,但由于ImageButtonStyle扩展了ButtonStyle,因此背景属性在ButtonStyle中设置。类似以下方式:

ImageButtonStyle style = new ImageButtonStyle();
style.up           = background;
style.down         = background;
style.checked      = background;
style.imageUp      = icon_up;
style.imageDown    = icon_down;
style.imageChecked = icon_checked;
style.unpressedOffsetY = -20; // to "not" center the icon
style.unpressedOffsetX = -30; // to "not" center the icon

ImageButton heartButton = new ImageButton(style);
ImageButton envelopeButton = new ImageButton(envelopeStyle);

对我而言,backround、icon_*是可绘制对象(Drawable)。但这只是基础部分,对我来说效果非常好。


4
您可以实现一个扩展ImageButton的自定义按钮类。 然后,如果您重载构造函数,您可以将imageUp、imageDown和background的Drawable或Texture传递给它:
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.scenes.scene2d.utils.SpriteDrawable;

public class myButton extends ImageButton
{   
    public myButton(Texture texture_up, Texture texture_down, Texture background)
    {
        super(new SpriteDrawable(new Sprite(texture_up)),
              new SpriteDrawable(new Sprite(texture_down)));

        this.setBackground(new SpriteDrawable(new Sprite(background));
    }
}

现在,您可以使用自己的Button类,并按以下方式实例化它:
Texture textureUp   = new Texture(Gdx.files.internal("data/image_up.png"));
Texture textureDown = new Texture(Gdx.files.internal("data/image_down.png"));
Texture background  = new Texture(Gdx.files.internal("data/background.png"));
MyButton myButton   = new MyButton(textureUp, textureDown, background);

也许您可以试着使用它,并了解您还可以用它做什么。只要确保图像具有正确的分辨率,背景不一定需要是图像。请尝试使用并发掘更多可能性。

你测试过这个吗?我尝试了这种方法,但它不能正确地工作。另一个得到更高赞的答案似乎是可行的方式。 - Ryan Stout

0

按键通常有三种状态:

imageDown - 当鼠标点击按钮时

imageUp - 当鼠标在按钮上释放时

imageChecked - 当鼠标悬停在按钮上时

在scene2d api中,目前还没有一种手动设置imageButton背景图像的方法,但如果您确实需要这样的功能,最好使用一个图像数组和一个索引来确定所需的图像,并使用sprite batch进行渲染,例如:

Texture[] images;
int currentImage;

我猜我的困惑来自于LibGDX API。使用 Button,它有三个状态的可绘制对象:up、down 和 checked。但是查看 ImageButton 时,它说“一个带有子图像的按钮以显示图像”。根据我的理解,这意味着 ImageButton 在已经有的三种 Drawable 状态之上具有一个 Image。这不是这种情况吗?如果不是,那是什么意思? - advice

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接