- Home /
Scaling GridLayoutGroup cells for multiple mobile aspect ratios
I have a Grid Layout Group as the content of a Scroll Rect. The grid is constrained to 3 columns. What I would like to do is have the grid cells scale their size uniformly across multiple aspect ratios. Basically, I just want to maintain the same spacing between each of the cells and the edges of the screen by adjusting their sizes.
Below is what it currently looks like when running the game in 9:16 and 10:16 aspect ratios. The 10:16 ratio has larger gaps on the sides.
I am not sure how to proceed so all help is appreciated.
Answer by eses · Sep 02, 2018 at 10:08 AM
Hi @danmw3
There are many threads, answers and links to other sites about this topic if you just google for this.
It might be, that GridLayoutGroup and LayoutElements don't work that great together...IIRC.
If that was so, you can at least use built-in OnRectTransformDimensionsChange method, which gets called when RectTransform change.
Calculate your element size from the column count, RT width, spacing and padding, then apply it to gridLayoutGroup cell size.
But it probably isn't that simple, if you now 3x? amount of grid items, what about landscape layout... and so on. Might not be issue if you keep it simple and stick with vertical only.
Something like this (spacing is not good but works for this example):
void OnRectTransformDimensionsChange ()
{
var w = rt.rect.width;
var spacing = gridLayoutGroup.spacing.x;
w -= spacing * 2f;
size = (w / cellsX);
// Optional size limits
// size = size < 32f ? 32f : size;
gridLayoutGroup.cellSize = new Vector2 (size, size);
}
I have been searching for well over two hours of issues similar to this. I have found a few, but none of them either had a solution for their specific situation or a solution in general that I could piece together.
I am not using LayoutElements for the grid, but I have seen other people try using them with little success.
This project only runs in portrait mode so that isn't a problem.
Either way, I have managed to figure this out without using the OnRectTransformDimensionsChange method because I only need to reposition everything on start.
Thanks for the help anyways.
@danmw3 - Ah. Ok. Anyway, I updated the answer with a code sample. It will give an idea what I meant, but it's not fully working for sure.
Your answer
Follow this Question
Related Questions
GridLayout Scaling Issues 1 Answer
How to Stretch objects in grid layout when screen size is changed 0 Answers
Scale Layout elements to fit screen 2 Answers
Why doesn't childing a gameobject to GridLayoutGroup at runtime align it properly? 1 Answer
Dynamically added buttons aren't aligned in GridLayoutGroup 0 Answers