Draw a logo with gradients with Ruby and Cairo 2008-03-21


UPDATE: I have posted yet another Cairo tutorial: Web2.0 style logo reflection with Ruby and Cairo

After this entry about drawing with Cairo I decided to play around some more. The following example uses the functions I included my previous entry (you'll need to include the require's and functions with the code below for it to work), and generates this logo:

Some variables for colors etc.:

h = 100
w = 300

blue   = [0.0,0.0,1.0, 1]
black = [0.0,0.0,0.0, 1]
shadow = [0.0,0.0,0.0, 0.2]
white  = [1.0,1.0,1.0, 1]
lblue   = [0.6,0.6,1.0,1]
dblue   = [0.0,0.0,0.2,1]

The main function follows below. First we set up the surface and create a gradient, the same way as last time:

cairo_image_surface(w,h, white) do |cr|

  rg1 = linear_gradient(0,15,0,h*0.8, :reflect, [0.0,blue],[0.4,lblue],[0.5,lblue],[0.5,dblue],[1.0,blue])

Then we select a font and set the size:

  cr.select_font_face("Arial", Cairo::FONT_SLANT_NORMAL, Cairo::FONT_WEIGHT_BOLD)
  cr.set_font_size(90.0)

Then we create a path of the text. If you want, you can just use "show_text" instead, but that draws the text directly. Using "text_path" is more flexible, since it turns the text into a path that can be manipulated all the same ways as any other path. In this case we draw the shadow first, using a translucent black:

  cr.move_to(18, 83)
  cr.text_path ("Hello");
  cr.set_source_rgba(shadow)
  cr.set_line_width(4)
  cr.stroke

Then we create the main text path a few pixels offset from the shadow, and fill it:

  cr.move_to(15, 80)
  cr.text_path ("Hello");
  cr.set_source(rg1)
  cr.fill_preserve

See how it's exactly the same as filling the path last time? Only this time the path consists of text instead of some lines.

Then all we have to do is to draw the border around the text and write it out to a file:

  cr.set_source_rgba(*black)
  cr.set_line_width(3)
  cr.stroke

  cr.target.write_to_png("test.png")
end


blog comments powered by Disqus