How do you dynamically resize a control so that it is still centered by its anchor?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By chanon

Suppose I have a ColorRect inside a Control.
I set the ColorRect’s anchors to
left 0.5, right 0.5, top 0, bottom 0

I adjust it in the editor view so the ColorRect is nicely centered in the Control.

Then suppose at run-time I want to resize the ColorRect’s width to be wider. How can I easily do this while keeping the ColorRect centered?

What I tried was to change the rect_size.x in code, but this just resulted in the ColorRect getting longer to the right but not centered.

I thought having anchors would mean resizing it would keep it centered?

:bust_in_silhouette: Reply From: chanon

I found a way. After changing the rect_size.x I need to call

set_anchors_and_margins_preset(Control.PRESET_CENTER, Control.PRESET_MODE_KEEP_SIZE)

On the ColorRect to ‘re-center’ it. I still wish there was another way as I think simple resizing should respect the anchors.

Thanks for your answer. Did you find a way of doing it without writing code? for example, if I want to grow a panel with animation…

bashan | 2020-03-28 20:41