How to scale a UI by using scripts?

By using scripts, how do I scale the Frame from this:


To this?

I also want them to be positioned in the center of the screen while being scaled.
The current size of the original frame is {0.16, 0},{0.21, 0} and position of the frame is {0.45, 0},{0.4, 0}

8 Likes

All the information can be found here GuiObject | Documentation - Roblox Creator Hub

You simply change the size to what you need (GuiObject | Documentation - Roblox Creator Hub), and then to center it you have to modify the position (GuiObject | Documentation - Roblox Creator Hub).

The position should always be {0.5, a},{0.5, b}, where

a = -frame.AbsoluteSize.X / 2 

and

b = -frame.AbsoluteSize.Y / 2 

in order to have it perfectly centered.

So you can do something like that to make it bigger:

frame.Size = UDim2.new(0.32, 0, 0.42, 0); -- modify these to what you like
frame.Position = UDim2.new(0.5, -frame.AbsoluteSize.X / 2, 0.5, -frame.AbsoluteSize.Y / 2);

and that to make it smaller again:

frame.Size = UDim2.new(0.16, 0, 0.21, 0); -- modify these to what you like
frame.Position = UDim2.new(0.5, -frame.AbsoluteSize.X / 2, 0.5, -frame.AbsoluteSize.Y / 2);

You can use TweenService (TweenService | Documentation - Roblox Creator Hub), to make the scaling process look smooth, because in my solution the GUI will be either big or small. TweenService will allow you to interpolate between these sizes while changing from one size to the other.

14 Likes

Thanks! :smiley:
One more question, what if I want the frame’s center always following the mouse’s center?

Edit: My ultimate goal is not tweening it, I’m creating a weapon crosshair where the crosshair image size is different for different weapons.

You can get the mouse position from

local plr = game.Players.LocalPlayer;
local mouse = plr:GetMouse();

local mouseX = mouse.X;
local mouseY = mouse.Y;

And finally apply these values to the position:

frame.Position = UDim2.new(0, mouseX - frame.AbsoluteSize.X / 2, 0, mouseY - frame.AbsoluteSize.Y / 2);
2 Likes

For that you can use a loop like a while loop (make sure to add a wait), and set the offset position of the frame which is {0, offsetX, 0, offsetY} to the Mouse.X and Mouse.Y (which would be in pixels.

Article about mouse.

1 Like

Instead of a loop I would use RenderStepped (RunService | Documentation - Roblox Creator Hub). This allows to update the position in every rendered frame so the movement is perfectly smooth.

local RunService = game:GetService("RunService")
 
RunService.RenderStepped:Connect(function()
	-- update position here
end)
2 Likes

Solved, Thanks for helping! :smiley:

2 Likes