- Home /
Fitting UI element height to content while expanding width to fill screen?
How can I accomplish this? I want to have an element that fits its height to its content and has its width expanded across the screen (canvas). I am able to do one of those things but can't figure out how to do both at the same time. I know I can expand the width with a horizontal or vertical layout group and use a content size fitter to fit the element's height to its child content but apparently these two components can't be mixed. Is there a way to do this with the gui system without writing extra code?
Answer by LW · Apr 27, 2018 at 06:28 PM
This may help you:
Create a Canvas
Set the Canvas Scaler UI Scale Mode to Scale with Screen Size
Add a child Game Object to the Canvas
Set the Content Size Fitter Horizontal to Unconstrained
Set the Content Size Fitter Vertical to Preferred Size
Set the child Rect Transform Min X anchor to 0 and the Max X anchor to 1
Set the child Rect Transform Left and Right to 0
Add both a Vertical Layout Group and a Content Size Fitter to the child Game Object
Set the Vertical Layout Group Spacing to 4,
Set the Vertical Layout Group Child Controls Size Width and Height to true
Set the Vertical Layout Group Child Force Expand Width and Height to false
Add a button (or any object really) as a child of the previous game Object
Add a Layout Element to the newly created button
Set the newly created button's Layout Element Preferred Width and Height to... (e.g. 160 and 30)
Duplicate the button
I hope that may help you!
Answer by fafase · Apr 27, 2018 at 07:12 PM
Place all your button in a container (it might be the parent object you mentioned).
Make your container with anchor min (0, 0) and max (1, 1). Set the Left. Top, Right and Bottom to 0. Now your parent box occupies the whole screen. You can also click the square icon above Anchor and then press Alt and press the bottom right icon. That will set it all to what I just described.
If you have a limited and constant amount of button, do not use a vertical layout group, it is convenient but adds computation for redrawing that you can avoid. Make them all children of the parent container object. Select them all four and set anchor min X to 0 and max X to 1. Then set left and right to 0 for all four of them.
Now comes the tricky part, for each from top to bottom set the anchors to:
minY : 0.75 maxY : 1
minY : 0.5 maxY : 0.75
minY : 0.25 maxY : 0.5
minY : 0 maxY : 0.25
If you end up with a weird amount of button like 7 of them, you can just put 1/7 then 2/7 then 3/7 and so on, unity will set the value for you. Once you set the all fine, select them all and set Top and Bottom values to 0.
This is it, they should occupy the whole width and each will use a quarter of the height. It will also rescale based on the screen dimensions, you can even change the ratio from landscape to portrait.
And it takes no additional component or code.