Monday, August 31, 2009

Ruby: Playing with Colour

Had an idea for a new twitter background.

I wrote it in ruby, using the rmagick API wrapper for ImageMagick.

Pretty straight forward:

  • make a big black background,

  • create a lot of random coloured squares and write the colour on them while you're at it,

  • write to jpeg file


Here's the code.

require 'rubygems'
require 'RMagick'
include Magick

buffer = Magick::Image.new(1700,1040) { self.background_color = "#000000" }

x = 10
y = 10
tone = [ '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F' ]

srand 1234
1118.times do
puts '* '+x.to_s+' '+y.to_s
red = rand(16)
green = rand(16)
blue = rand(16)
ligthness = red+green+blue
co = '#'+tone[red]+tone[green]+tone[blue]
patchObj = Magick::Draw.new
patchObj.fill = co
patchObj.polygon(x,y,x,y+30,x+30,y+30,x+30,y)
patchObj.matte(3,3,PaintMethod::ReplaceMethod)
patchObj.draw(buffer)
textObj = Magick::Draw.new
textObj.font = './fonts/Ghoul.ttf'
textObj.pointsize=12
if ligthness > 25 || green > 11
textObj.fill = '#000'
else
textObj.fill = '#fff'
end
textObj.text(x, y+12, co)
textObj.draw(buffer)
x = x+40
if x > 1690
x = 10
y = y+40
end
end

buffer.display
buffer.write("random_colour.jpg")

exit

Enjoy.

#ToDo: use a resource pool so don't have the cost of creating over 2K Draw objects.

No comments: