Attention: Here be dragons
This is the latest
(unstable) version of this documentation, which may document features
not available in or compatible with released stable versions of Godot.
Checking the stable version of the documentation...
大小和锚点
如果一个游戏总是用同一分辨率在同样的设备上运行, 摆放控件将是一个简单的事, 只要逐个设置它们的位置属性和大小属性即可. 不幸的是, 能像这样处理的情况很少.
虽然某些配置可能比其他配置更常见,但手机、平板电脑和便携式游戏机等设备可能会有很大差异。因此,我们通常需要考虑不同的宽高比、分辨率和用户缩放比例。
有几种方法来处理这个问题, 但现在, 让我们想象一下, 屏幕分辨率已经改变, 控件需要重新定位. 有的需要跟随屏幕的底部, 有的需要跟随屏幕的顶部, 也有的需要跟随左右边距.

这是通过编辑控件的 锚点偏移量 来实现的,其行为类似于边距。要访问这些设置,你需要先选择 自定义 锚点预设。
每个控件都有四个边距:左、右、底、顶,分别与控件的边缘相对应。默认情况下,它们都表示相对于父控件的左上角或(在没有父控件的情况下)视口的像素距离。

因此,要使控件变宽,可以增大右边距和/或减小左边距。这使你可以设置控件的精确位置和形状。
The anchor properties adjust where the offsets are relative to.
Each offset has an individual anchor that can be adjusted from the
beginning to the end of the parent. So the vertical (top, bottom) anchors
adjust from 0.0
(top of parent) to 1.0
(bottom of parent) with 0.5
being
the center, and the control offsets will be placed relative to that
point. The horizontal (left, right) anchors similarly adjust from left to
right of the parent.
请注意,当你希望控件的边缘位于锚点的上方或左侧时,必须将边距值更改为负数。
For example: when horizontal anchors are changed to 1.0
, the offset values
become relative to the top-right corner of the parent control or viewport.

调整两个水平或两个垂直锚点到不同的值,将使控件在父控件改变大小时也随之改变。在这里,控件的右下角锚定到父控件的右下角,而左上角的控件边距仍然锚定到父控件的左上角,因此在调整父控件大小时,控件将始终覆盖父控件,并留有 20 像素的边距:

使控件居中
要将控件在其父控件内居中,请将锚点都设置为 0.5
, 每侧边距为其相关尺寸的一半。例如, 下面的代码显示了如何将 TextureRect 在它的父节点内居中:
var rect = TextureRect.new()
rect.texture = load("res://icon.png")
rect.anchor_left = 0.5
rect.anchor_right = 0.5
rect.anchor_top = 0.5
rect.anchor_bottom = 0.5
var texture_size = rect.texture.get_size()
rect.offset_left = -texture_size.x / 2
rect.offset_right = texture_size.x / 2
rect.offset_top = -texture_size.y / 2
rect.offset_bottom = texture_size.y / 2
add_child(rect)
var rect = new TextureRect();
rect.Texture = ResourceLoader.Load<Texture>("res://icon.png");
rect.AnchorLeft = 0.5f;
rect.AnchorRight = 0.5f;
rect.AnchorTop = 0.5f;
rect.AnchorBottom = 0.5f;
var textureSize = rect.Texture.GetSize();
rect.OffsetLeft = -textureSize.X / 2;
rect.OffsetRight = textureSize.X / 2;
rect.OffsetTop = -textureSize.Y / 2;
rect.OffsetBottom = textureSize.Y / 2;
AddChild(rect);
将每个锚定值设置为0.5, 将边缘的参考点移动到父锚点的中心. 在此基础上, 我们设置了负边距, 以便控件获得其自然大小.
布局预设
除了手动调整边距和锚点的值之外,你还可以使用视口上方工具栏中的“布局”菜单。其中有居中等诸多选项,可以用来对齐并调整节点的大小。
