Running with Shoes – 2D Graphics and Animation

I’ve already gone over the basic UI features of the Shoes toolkit. Shoes is a nice little domain specific language for developing GUI applications in Ruby. Here I’ll go over some of the 2D graphics and animation capabilities in Shoes.

Shoes has a light weight 2D support where you can draw lines, rectangles, and circles. To create an application that draws a line we can execute the following bit of code. :width => 200, :height => 200 do
# line x1, y1, x2, y2
line 20, 40, 60, 80

To draw an oval insert the following code inside the shoes code block. :width => 200, :height => 200 do
# oval center_x, center_y, width, height
oval 50, 100, 100, 50

And to a simple rectangle, you can do so by using the rect method. :width => 200, :height => 200 do
# rect top_x, top_y, with, height
rect 100, 100, 30, 10

Shoes also supports the animate method which can be used, as it’s name applies, to repeatably call a block of code that animates some graphics. The animate method takes a parameter, the number of frames per second. For example, to draw a new image once a second we can call animate(1). To draw an image twice a second call animate(2). Here is a simple example of the animate method in action.

text_field = nil :width => 200, :height => 200 do
text_field = text
animate(1) do

The above piece of code creates a text field and updates the value of the text field with the current time once a second. This way you can animate a simple text-based clock.

Here is another animation example. The following code draws a rectangle. The rectangle is moved twice a second to a random location within the application window. This code uses the fill and stroke methods, which accept arguments to define the fill and stroke color respectively. You can also use the strokewith method to set the width of the pen stroke. Also notice that the following example invokes the width and height methods which return the current width and height of the application window.

moving_box = nil :width => 200, :height => 200 do
# fill red, green, blue, alpha
fill 1.0, 0.5, 1.0, 1.0
stroke 0.5, 0.5, 1.0, 1.0
strokewidth 5
moving_box = rect 10, 10, 20, 20

animate(2) do
x = (0..width-20).rand
y = (0..height-20).rand
moving_box.move x, y

As you can see, it is easy to draw 2D graphics using Shoes.

Technorati Tags: , , , , , , ,

Related posts:

  1. Running with Shoes – Colorfy
  2. Running with Shoes – 2D Examples
  3. Running with Shoes – A Mini GUI Toolkit
  4. Running with Shoes – Form and Function
  5. Running with Shoes – Show Me More
  6. Running with Shoes – Transform

3 Responses to “Running with Shoes – 2D Graphics and Animation”

Leave a Reply