Jump to content

Recommended Posts

Posted

While coding my lua GUI I found that I needed to be able to fill many 2d polygons. After looking at quite a few algorithms (I am very bad at math), I found one created in lua and felt that I needed to share.

 

It was converted from the Corona lua which was in turn converted from PSP lua. I have modified it to work without change in Leadwerks

 

See here for examples on how it works: http://forums.coronalabs.com/topic/8084-drawing-a-polygon-with-a-fill/

 

function rgbatovec4scalar(rgb,a)
return Vec4(rgb[1]/256,rgb[2]/256,rgb[3]/256,a/256)
end

function paintPoly(poly, xoffset, yoffset, rgba)
-- [url="http://forums.coronalabs.com/topic/8084-drawing-a-polygon-with-a-fill/"]http://forums.coronalabs.com/topic/8084-drawing-a-polygon-with-a-fill/[/url]
local math_floor = math.floor
local math_min = math.min
local math_max = math.max
local polyGroup = {}

local n = table.getn(poly)

local minY = poly[1].y
local maxY = poly[1].y

for i = 2, n do
	minY = math_min(minY, poly[i].y)
	maxY = math_max(maxY, poly[i].y)
end

for y = minY, maxY do

	local ints = {}
	local int = 0
	local last = n

	for i = 1, n do
		local y1 = poly[last].y
		local y2 = poly[i].y
		if y1 < y2 then
			local x1 = poly[last].x
			local x2 = poly[i].x
			if (y >= y1) and (y < y2) then
				int = int + 1
				ints[int] = math_floor((y - y1) * (x2 - x1) / (y2 - y1) + x1)
			end
		elseif y1 > y2 then
			local x1 = poly[last].x
			local x2 = poly[i].x
			if (y >= y2) and (y < y1) then
				int = int + 1
				ints[int] = math_floor((y - y2) * (x1 - x2) / (y1 - y2) + x2)
			end
		end
		last = i
	end

	local i = 1
	while i < int do
polyfillcontex = Context:GetCurrent()
polyfillcontex:SetColor(rgbatovec4scalar(rgba,rgba[4]))
polyfillcontex:DrawLine(ints[i] + xoffset, y + yoffset, ints[i + 1] + xoffset, y + yoffset)
		i = i + 2
	end
end

return polyGroup
end

  • Upvote 1

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...