Rainbow gradient using EditableImage

After hours of finding the algorithm for linear gradients and polylinear gradients, I have made a rainbow gif using editableimage.


How could I improve this?

Source, for the greedy people
--!strict
local camera = workspace.CurrentCamera

local image = Instance.new 'EditableImage'
image.Size = Vector2.new(100, 100)

local imageLabel = Instance.new 'ImageLabel'
imageLabel.Size = UDim2.fromScale(0.3, 0.3)
image.Parent = imageLabel
imageLabel.Parent = script.Parent

local function ColorToRGBA(color: Color3|BrickColor, alpha: number?)
	local Color3 = if typeof(color) == "Color3" then color else color.Color
	alpha = if alpha ~= nil then alpha else 1

	return Color3.R, Color3.G, Color3.B, alpha
end
local function RGBFromColor3(color: Color3)
	return color.R * 255, color.G * 255, color.B * 255
end
local function LinearGradient(start: Color3, endingColor: Color3, accuracy: number)
	local startRGB = {RGBFromColor3(start)}
	local endRGB = {RGBFromColor3(endingColor)}
	
	local RGBlist = {startRGB}
	
	for t = 1, accuracy do
		local array = {}
		for j = 1, 3 do
			array[j] = math.floor(startRGB[j] + (t / (accuracy - 1)) * (endRGB[j] - startRGB[j]))
		end
		table.insert(RGBlist, array)
	end
	return RGBlist
end
local function PolylinearGradient(colors: {Color3}, accuracy: number)
	accuracy = math.floor(accuracy / (#colors - 1))
	local gradientList = LinearGradient(colors[1], colors[2], accuracy)
	
	if #colors > 1 then
		for color = 2, #colors - 1 do
			local current = LinearGradient(colors[color], colors[color + 1], accuracy)
			local OK = false
			for _, value in current do
				if not OK then
					OK = true -- skip first color to reduce repetitiveness
					continue
				end
				table.insert(gradientList, value)
			end
		end
	end
	return gradientList
end

local imagePixels = {}
local generated = {}
for step = 0, 12, 1 do
	table.insert(generated, Color3.fromHSV((30 * step) / 360, 1, 1))
end

while true do
	local removed = table.remove(generated, #generated) :: Color3
	for i, v in table.clone(generated) do
		generated[i + 1] = v
	end
	generated[1] = removed
	
	local gradientOnce = PolylinearGradient(
		generated,
		image.Size.X * image.Size.Y
	)
	
	local gradient = {}
	for i = 1, image.Size.Y do
		for _, value in gradientOnce do
			table.insert(gradient, value)
		end
	end
	
	local index2 = 1
	for index = 1, image.Size.X * image.Size.Y * 4, 4 do
		index2 += 1
		imagePixels[index + 0],
			imagePixels[index + 1],
			imagePixels[index + 2] = ColorToRGBA(
				Color3.fromRGB(table.unpack(gradient[index2]))
			)
		imagePixels[index + 3] = 1
	end
	
	image:WritePixels(Vector2.zero, image.Size, imagePixels)
	task.wait()
end
7 Likes