size_and_anchors.rst 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. .. _doc_size_and_anchors:
  2. Size and anchors
  3. ================
  4. If a game was always going to be run on the same device and at the same
  5. resolution, positioning controls would be a simple matter of setting the
  6. position and size of each one of them. Unfortunately, that is rarely the
  7. case.
  8. Only TVs nowadays have a standard resolution and aspect ratio.
  9. Everything else, from computer monitors to tablets, portable consoles
  10. and mobile phones have different resolutions and aspect ratios.
  11. There are several ways to handle this, but for now, let's just imagine
  12. that the screen resolution has changed and the controls need to be
  13. re-positioned. Some will need to follow the bottom of the screen, others
  14. the top of the screen, or maybe the right or left margins.
  15. .. image:: img/anchors.png
  16. This is done by editing the *margin* properties of controls. Each
  17. control has four margins: left, right, bottom and top. By default, all of
  18. them represent a distance in pixels relative to the top-left corner of
  19. the parent control or (in case there is no parent control) the viewport.
  20. .. image:: img/margin.png
  21. When horizontal (left, right) and/or vertical (top, bottom) anchors are
  22. changed to 1, the margin values become relative to the bottom-right
  23. corner of the parent control or viewport.
  24. .. image:: img/marginend.png
  25. Here, the control is set to expand its bottom-right corner with that of
  26. the parent, so when re-sizing the parent, the control will always cover
  27. it, leaving a 20 pixel margin:
  28. .. image:: img/marginaround.png
  29. Centering a control
  30. -------------------
  31. To center a control in its parent, set its anchors to 0.5 and each margin
  32. to half of its relevant dimension. For example, the code below shows how
  33. a TextureRect can be centered in its parent:
  34. ::
  35. var rect = TextureRect.new()
  36. rect.texture = load("res://icon.png")
  37. rect.anchor_left = 0.5
  38. rect.anchor_right = 0.5
  39. rect.anchor_top = 0.5
  40. rect.anchor_bottom = 0.5
  41. var texture_size = rect.texture.get_size()
  42. rect.margin_left = -texture_size.x / 2
  43. rect.margin_right = -texture_size.x / 2
  44. rect.margin_top = -texture_size.y / 2
  45. rect.margin_bottom = -texture_size.y / 2
  46. add_child(rect)
  47. Setting each anchor to 0.5 moves the reference point for the margins to
  48. the center of its parent. From there, we set negative margins so that
  49. the control gets its natural size.