- Home /
Universal Method of finding pixel dimensions of UI elements
Assuming we're considering UI elements nested under a screen-space overlay canvas. Is there a universal method of getting the exact dimensions of an element E in pixels?
Please consider all the possible cases:
All possible anchor settings
All possible pivot settings
Elements that are children of a
layout groupElements that contain content size
fittersThe Canvas has different UI scale modes
I've tried all the built in methods/variables with RectTransform and none of them seem to work for all cases. Is there an easy method to get the pixel dimensions?
Answer by nabrown3 · Sep 30, 2015 at 06:08 PM
Ok, so the real cause of my inability to do this correctly came from the fact that UI elements with content size fitters need 1 frame to update after children are added to them before you can accurately get their sizes. Knowing this, you can just use RectTransform.rect to get accurate coordinates (assuming you do so one frame after adding anything to the element).
Wanted to add on here in case anyone comes across this thread. This worked perfectly for me.
$$anonymous$$y item had 0 width and size on load and was using a content size fitter to make it dynamic, I had no idea why it had no size. I ran a coroutine a frame after my item is initialised and was able to get the pixel coordinates after it adjusted.
Cheers for the answer.
You don't have to wait. You can force it with: Canvas.ForceUpdateCanvases();
or LayoutRebuilder.ForceRebuildLayoutImmediate((RectTransform)transform);
Your answer
Follow this Question
Related Questions
Unity 4.6 UI Canvas width & height 2 Answers
Swapping UI image element positions 1 Answer
RectTransform rounding? 0 Answers
How to align pixel art with UI system ? 0 Answers