Repeating an image background.

Basically I want to repeat a small 4x4 image onto a hud that is a different size for all resolutions. Now I have the hud setup so it is a multiple of four, but I have two questions. Would I do a loop with surface.DrawTexture and create a bunch of textures across and down until it is the solid background, and would that be a small performance hit having a couple hundred 4x4 textures being placed on a hud.

I’m really not sure how to go about this so any advice would be appreciated.

Try something like this, perhaps?


local w,h = 4,4
for i = 1, ScrW(), ScrW()/w do
	for n = 1, ScrH(), ScrH()/h do
		surface.DrawTexture(i,n,w,h)
	end
end

That’s what I meant thanks for that, but wouldn’t it be a performance hit doing that every frame just for a simple background on a hud?

Point. You could do something like this, so long as you don’t need to update the background too much:


local drawpos = {}
local w,h = 4,4
local key = 1
for i = 1, ScrW(), ScrW()/w do
	for n = 1, ScrH(), ScrH()/h do
		drawpos[key] = {i,n}
		key = key + 1
	end
end

hook.Add("HUDPaint","DrawBackground",function()
	for _,v in ipairs(drawpos) do
		surface.DrawTexture(v[1],v[2],w,h)
	end
end)

Or if you didn’t like hooks, you could do something like this:


local drawpos = {}
local w,h = 4,4
local key = 1
for i = 1, ScrW(), ScrW()/w do
	for n = 1, ScrH(), ScrH()/h do
		drawpos[key] = {i,n}
		key = key + 1
	end
end

local function DrawBackground()
	local frame = vgui.Create("DFrame")
	frame:SetSize(ScrW(),ScrH())
	frame:SetPos(0,0)
	frame.Paint = function()
		for _,v in ipairs(drawpos) do
			surface.TexturedRect(v[1],v[2],w,h)
		end
	end
end

Only define poly once to save on the garbage, but:

[lua]
poly = {
{
x = x1,
y = y1,
u = 1,
v = 1,
},
{
x = x1 + w
y = y1,
u = w / size,
v = 1,
},
{
x = x1 + w,
y = y1 + h,
u = w / size,
v = h / size,
},
{
x = x1,
y = y1 + h,
u = 1,
v = h / size,
}
}

surface.SetDrawColor( 255, 255, 255, 255 )
surface.SetTexture( tex )

surface.DrawPoly( poly )
[/lua]

Should do what you want. Untested, but you get the idea.

Thanks, got it working.