如何在 gdscript 中设置按钮边框?

How to set borders on buttons in gdscript?

我创建了按钮(带有扩展按钮)。如何使用 Stylebox 专门设置边框?

extends Button


# Declare member variables here. Examples:
# var a = 2
# var b = "text"

func init(num,_x,_y):
    text=str(num)
    connect("pressed", self, "ButtonPressed")
    var new_stylebox_normal = get_stylebox("normal").duplicate()
    var stylebox_flat = new_stylebox_normal as StyleBoxFlat
    stylebox_flat.border_width_left=1

    add_stylebox_override("normal",stylebox_flat)

该按钮将有一个 StyleBoxTexture not a StyleBoxFlat。因此,如果您 运行 提供的代码,stylebox_flat 将为空。如果你想设置一个StyleBoxFlat,你需要创建一个新的:

var stylebox_flat := StyleBoxFlat.new()
stylebox_flat.border_width_left = 1
add_stylebox_override("normal", stylebox_flat)

当然,StyleBoxTexture没有border_width_left 属性。如果你真的想修改按钮样式,你需要给 StyleBoxTexture.

添加边框

要具有 StyleBoxTexture 的边框,它们必须存在于纹理中。 StyleBoxTexture 的文档说:

Texture-based nine-patch StyleBox, in a way similar to NinePatchRect. This stylebox performs a 3×3 scaling of a texture, where only the center cell is fully stretched. This makes it possible to design bordered styles regardless of the stylebox's size.

看看 NinePatchRect 是如何工作的,以供参考,就像 StyleBoxTexture 一样。

是这样的:你创建了画有边框的纹理,然后在纹理上配置“边距”,将被视为边框。然后Godot会将纹理切割成九个独立展开的patch:

  • 上下边框水平扩展。
  • 左右边框垂直展开。
  • 四个角完全没有展开
  • 中心展开填充。

StyleBoxTexture 中的属性为:margin_leftmargin_rightmargin_topmargin_bottom是的,还有一些名为 expand_margin_* 的属性,但这些不是您想要的。这很混乱,我知道。我希望它的名称与 NinePatchRect (patch_margin_*).

中的名称相同

您还将配置扩展的工作方式(“轴拉伸模式”)。它可以通过拉伸纹理、平铺或两者的组合来确保平铺的数量是整数。其属性是 axis_stretch_horizontalaxis_stretch_vertical.

既然我们在谈论修改按钮样式,我们也可能在谈论从 GDScript 编辑纹理。我对 How can I bake 2D sprites in Godot at runtime? 的回答应该可以帮助您入门,如果您希望我对此进行扩展,请告诉我。


我发现这个视频展示了 NinePatchRectNinePatchRect - Godot Tutorial. And here is one showing how to set the StyleBoxTexture: Godot Expanding TextBox and StyleBoxTexture Resource。您正在尝试这样做,但是来自代码。

事实上,我不知道您为什么要尝试从代码中执行此操作。但是,要知道您可以创建一个新的 StyleBoxTextureStyleBoxFlat 资源(例如,在“文件系统”面板中,二次单击会带来一个带有“新建资源...”选项的上下文菜单),在Inspector 面板(或者在 StyleBoxTexture 的情况下应该出现的 TextureRegion 面板中的可视化编辑器)。

您也可以将资源设置为检查器面板中的自定义按钮(或者您可以简单地从代码加载和设置资源)。

我提醒你还有 Theme 资源。


对了,你的意思是写_init吗? Godot 将尝试调用脚本中定义的 _init 方法作为初始化。需要注意的是,附加到节点的脚本的 _init 必须没有参数(因为在实例化场景时传递了 none,也没有办法传递任何参数)。