+2 votes

Hi, I am trying to create a NinePatchRect background for my TextLabel. Both of them should be centered on the screen

My problem is I can't manage to make sure it's always larger than my text.

My current approach is like this:

TreeStructure:

  • CenterContainer

    • NinePatchRect: Background

      • Label: Text

Code:

export(String) var text setget set_text

func set_text(newText):
    if has_node("Background/Text") and newText:
        var textNode = get_node("Background/Text")
        if textNode:
            textNode.text = newText
            call_deferred("_adaptLabelSize", textNode)
        text = newText



func _adaptLabelSize(textNode):
    var newminSize = textNode.rect_size.x + textNode.margin_left * 2
    rect_min_size.x = newminSize

func _ready():
    set_text(text)

My idea was to make the size of the background adapt each time the text gets changed. The problem is, that if I set textNode.text, the size of the textLabel isn't changed when I use it to determine newMinSize, even if I call it deferred.

What can I do?

asked Sep 20, 2018 in Engine by TobiLa (160 points)

1 Answer

0 votes

I don't think you need any code for this (apart from the set_text for the label).

I couldn't get it working with a center container - it kept my nine_patch_rect at it's minimum size regardless of the size flags. My working setup looks like this:

margin_container
  nine_patch_rect
  center_container
    label

When the text inside the label expands, the label's minimum size increases, forcing the center_container to expand and therefore forcing the margin_container to expand. The nine_patch_rect has size flags set to fill (the default) so its size follows the margin_container's size (within the margin specified, of course).

You may want another margin_container that the center_container is inside so you can ensure that even if the text expands it won't hit the edges of the ninepatch - this solves the "make sure it's always larger than the text" problem:

margin_container
  nine_patch_rect
  margin_container
    center_container
      label
answered Oct 6, 2018 by markopolo (618 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.