mirror of
https://github.com/godotengine/godot-docs.git
synced 2026-01-03 05:48:42 +03:00
Add a section to "Size and anchors" for centering a control in its parent
Perhaps the most common task possible has no documentation on this page.
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
.. _doc_size_and_anchors:
|
||||
|
||||
Size and anchors
|
||||
----------------
|
||||
================
|
||||
|
||||
If a game was always going to be run on the same device and at the same
|
||||
resolution, positioning controls would be a simple matter of setting the
|
||||
@@ -38,3 +38,28 @@ it, leaving a 20 pixel margin:
|
||||
|
||||
.. image:: img/marginaround.png
|
||||
|
||||
Centering a control
|
||||
-------------------
|
||||
|
||||
To center a control in its parent, set its anchors to 0.5 and each margin
|
||||
to half of its relevant dimension. For example, the code below shows how
|
||||
a TextureRect can be centered in its parent:
|
||||
|
||||
::
|
||||
|
||||
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.margin_left = -texture_size.x / 2
|
||||
rect.margin_right = -texture_size.x / 2
|
||||
rect.margin_top = -texture_size.y / 2
|
||||
rect.margin_bottom = -texture_size.y / 2
|
||||
add_child(rect)
|
||||
|
||||
Setting each anchor to 0.5 moves the reference point for the margins to
|
||||
the center of its parent. From there, we set negative margins so that
|
||||
the control gets its natural size.
|
||||
|
||||
Reference in New Issue
Block a user