[help] Dynamically generate gradient
Posted: Sat Jun 01, 2013 6:45 pm
how can I draw a gradient at runtime?
Thank you ...
Thank you ...
Code: Select all
local function Gradient(from, to, orientation)
orientation = orientation or 'horizontal'
local d = 1
if orientation == 'vertical' then
d = 0
elseif orientation ~= 'horizontal' then
error('invalid orientation: ' .. tostring(orientation))
end
local img = love.image.newImageData(1+d, 2-d)
print(orientation, d, 1-d, 1+d, 1+(d-1))
img:setPixel(0,0, from[1], from[2], from[3], from[4] or 255)
img:setPixel(d,1-d, to[1], to[2], to[3], to[4] or 255)
img = love.graphics.newImage(img)
img:setFilter('linear', 'linear')
return {
draw = function(x,y, w,h, r, ox,oy, kx,ky)
ox = (ox or 0) / w
oy = (oy or 0) / h
love.graphics.draw(img, x,y, r or 0, w/(1+d), h/(2-d), ox,oy, kx,ky)
end
}
end
function love.load()
gradient = Gradient({40,85,175}, {140,218,234})
gradient2 = Gradient({200,100,30}, {80,200,50}, 'vertical')
end
function love.draw()
gradient.draw( 10,10, love.graphics.getWidth()-10,100)
gradient2.draw(10,120, 150,150)
end
Code: Select all
function newColor(r,g,b,a)
local c = {}
c.red = r
c.green = g
c.blue = b
if a == nil then
c.alpha = 255
else
c.alpha = a
end
return c
end
function makeGradient(width,height,startColor,endColor)
local rcalc = endColor.red - startColor.red
local gcalc = endColor.green - startColor.green
local bcalc = endColor.blue - startColor.blue
local acalc = endColor.alpha - startColor.alpha
local i = 0
local r
local g
local b
local a
local color = love.graphics.getColor()
local gradient = love.graphics.newCanvas(width,height)
love.graphics.setCanvas(gradient)
while i < width do
r = startColor.red + (i * rcalc / width)
g = startColor.green + (i * gcalc / width)
b = startColor.blue + (i * bcalc / width)
a = startColor.alpha + (i * acalc / width)
love.graphics.setColor(r,g,b,a)
love.graphics.rectangle('fill',i, 0, 1, height)
i = i + 1
end
love.graphics.setCanvas()
return gradient
end
Code: Select all
function love.load()
rrt = makeGradient(800,600,newColor(255,0,0),newColor(0,255,0))
end
function love.draw()
love.graphics.draw(rrt)
end