PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience

Centering GUI Elements on Screen

Centering GUI Elements on Screen

Jun 29 2018, 4:51 PM PST

Problem

You want to position a GUI in the center of the screen.

Solution

Use the UDim2.new function and use the Scales.

local frame = Instance.new('Frame')
frame.Size = UDim2.new(0, 100, 0, 100)
frame.Position = UDim2.new(.5, -50, .5, -50)

Discussion

Here we are setting the size of a Frame to be 100x100 pixels. Next, we set the Position to have a UDim2 which has an X and Y Scale component of ½ (the middle of the screen) and X and Y Offset components of -50. The Scale components use relative to the screen so 0 would be all the way to the left or top and 1 would be to the bottom or right. Making that ½ on each axis would make it perfectly in the center. Or would it? Sizing occurs from the top left of the frame, so that would make the top right corner of the frame be the center. Most likely we want the frame itself to be centered.

To remedy this problem we set the Offset components of the position to be negative ½ of the size of each axis.

Think of it this way, we want to get the center of the frame in the center of the screen. The center of the frame would be ½ of each axis. Now we have the frame’s top left-hand corner positioned in the center of the screen. We must use subtraction in order to orient it into the center so we take the negative of that.


To learn more about positioning, check out our Articles/Intro to GUIs|Intro to GUIs for a more comprehensive explanation.

Tags:
  • gui
  • coding
  • script