大小和锚定点

如果一个游戏总是用同一分辨率在同样的设备上运行, 摆放控件将是一个简单的事, 只要逐个设置它们的位置属性和大小属性即可。不幸的是, 能像这样处理的情况很少。

如今只有电视机有标准分辨率和纵横比。而其他所有设备,从计算机显示器到平板电脑、便携游戏主机和手机等等,都有不同的分辨率和纵横比。

There are several ways to handle this, but for now, let’s just imagine that the screen resolution has changed and the controls need to be re-positioned. Some will need to follow the bottom of the screen, others the top of the screen, or maybe the right or left margins.

../../_images/anchors.png

This is done by editing the margin properties of controls. Each control has four margins: left, right, bottom and top. By default, all of them represent a distance in pixels relative to the top-left corner of the parent control or (in case there is no parent control) the viewport.

../../_images/margin.png

When horizontal (left, right) and/or vertical (top, bottom) anchors are changed to 1, the margin values become relative to the bottom-right corner of the parent control or viewport.

../../_images/marginend.png

Here, the control is set to expand its bottom-right corner with that of the parent, so when re-sizing the parent, the control will always cover it, leaving a 20 pixel margin:

../../_images/marginaround.png

Centering a control

要将控件集中到其父控件中,其锚定值为0.5,每个边距为其相关尺寸的一半。例如,下面的代码显示了如何将纹理矩形居中到它的父节点:

  1. var rect = TextureRect.new()
  2. rect.texture = load("res://icon.png")
  3. rect.anchor_left = 0.5
  4. rect.anchor_right = 0.5
  5. rect.anchor_top = 0.5
  6. rect.anchor_bottom = 0.5
  7. var texture_size = rect.texture.get_size()
  8. rect.margin_left = -texture_size.x / 2
  9. rect.margin_right = -texture_size.x / 2
  10. rect.margin_top = -texture_size.y / 2
  11. rect.margin_bottom = -texture_size.y / 2
  12. add_child(rect)

将每个锚定值设置为0.5,将边缘的参考点移动到父锚点的中心。在此基础上,我们设置了负边距,以便控件获得其自然大小。