+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:


  • CenterContainer

    • NinePatchRect: Background

      • Label: Text


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():

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?

in Engine by (205 points)

1 Answer

+4 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:


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:

by (648 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 Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.