I need help with a dynamicly sized draw.RoundedBox
3 replies, posted
I am trying to make a rounded box for a hud that changes its width depending on the contents. The contents are only text, (but on 2 lines) and is aligned to center.
I want the rounded box to adjust its size as if it were aligned to the center depending on the length of the text.
How would I go about doing this?
Use [url=http://wiki.garrysmod.com/page/surface/GetTextSize]surface.GetTextSize[/url] to figure out the size of the text and size the box accordingly.
You want to start by turning your two lines into variables.
[lua]
local LineOne = "Welcome to the server."
local LineTwo = "Enjoy your stay!"
[/lua]
Next would be getting the size of that text, width & height, and storing those to other variables.
[lua]
surface.SetFont("default") --Font must be set before getting the size, or the size will come out wrong.
local w, h = surface.GetTextSize(LineOne) --Line one dimensions.
local ww, hh = surface.GetTextSize(LineTwo) --Line two dimensions.
[/lua]
Next, the math would come in, find out which line has a longer width.
[lua]
local LongestLine = math.max(w, ww)
[/lua]
To go above and beyond, create another variable to add space between the edge of the box and text.
[lua]
local Padding = 4
local Spacing = 2
[/lua]
With all that you can achieve something neat and simple like this:
[lua]
local LineOne = "Welcome to the server."
local LineTwo = "Enjoy your stay!"
surface.SetFont("default") --Font must be set before getting the size, or the size will come out wrong.
local w, h = surface.GetTextSize(LineOne) --Line one dimensions.
local ww, hh = surface.GetTextSize(LineTwo) --Line two dimensions.
local LongestLine = math.max(w, ww)
local Padding = 4
local Spacing = 2
hook.Add("HUDPaint", "My text box script.", function()
local BoxWidth = LongestLine+(Padding*2)
local BoxHeight = (h+hh)+(Padding*2)
draw.RoundedBox(4, 0, 0, BoxWidth, BoxHeight, color_black)
draw.SimpleText(LineOne, "default", BoxWidth*0.5, Padding+(h*0.5), color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
draw.SimpleText(LineTwo, "default", BoxWidth*0.5, Padding+h+Spacing+(hh*0.5), color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end)
[/lua]
[IMG]http://s24.postimg.org/gdc4qbohd/image.png[/IMG]
Resources that will help you:
[URL]http://wiki.garrysmod.com/page/surface/GetTextSize[/URL]
[URL]http://wiki.garrysmod.com/page/math/max[/URL]
[URL]http://wiki.garrysmod.com/page/hook/Add[/URL]
Thanks guys for the help, much appreciated.
Sorry, you need to Log In to post a reply to this thread.