Color Parsing

June 30, 2008 | color, images

You can load an image, grab an array of colors from it, and then apply those colors to other objects on the canvas.

#!/usr/local/bin/macruby

framework 'cocoa'
require 'rubygems'
require 'hotcocoa/graphics'
include HotCocoa
include Graphics

# set up the canvas and font
canvas = Canvas.new :type => :image, :filename => 'parsing.png', :size => [400,400]
canvas.background(Color.black)
canvas.shadow

# load an image and select 100 random colors
image = Image.new('italy.jpg')
randomcolors = image.colors(100)

# create a 20x20 square at 0,0
square = Path.new.rect(0,0,20,20,:center)

# randomize the color, scale, and rotation of the square
square.randomize(:fill, randomcolors)
square.randomize(:scale, 1.0..5.0)
square.randomize(:rotation, 0..360)

# draw 100 squares and the original image
canvas.grid(square,10,10)
image.fit(120,120)
canvas.draw(image)
canvas.save