Creating a Figure in CupDraw

In this series of tutorials we will show how to create diagram editors using CupDraw. In this first tutorial we will code a Rectangle figure and a Tool to create it.

Creating a BASIC Figure in Cupdraw consists in 2 basic steps:

  1. Define the visual aspects of the figure.
  2. Define the tool that creates the figure.

Before we start, copy the empty project to start a new one.

Define the visual aspects of the figure

To create a figure simply subclass the Figure class and implement the method (void) drawRect: (CGRect) rect on: (id) context

In our case we are going to create a SimpleRectangleFigure, so we will need to draw the background of the rectangle and the border. This can be done simply as follows:

All figures come with 2 predefined instance variables for the foreground and background colors that can be configured to paint it. We will define them as black and white in the initialization method as follows:

Great! so we have our figure coded, now let’s define the tool that creates the figure.

Define the tool that creates the figure

A Tool is responsible for interpreting events/gestures and instantiating the Figure. CupDraw comes with some abstract classes that can help you create some basic tools quickly. In our example we will extend AbstractCreateFigureTool and implement a simple method for creating the rectangle with a default width and height when the user clicks in the Drawing. We implement the – (void) createFigureAt: (id) aPoint on: (id) aDrawing method as follows:

The first line creates a default frame for the given point and then we instantiate our SimpleRectangleFigure. Then we add the rectangle to the given Drawing and we active the Selection tool so that the next click is handle by the Selection tool. If you want to stick to this tool so that multiple clicks create multiple rectangles, you can remove the last line.

The last thing is to add the Tool to the toolbox in the AppController, we can do that by simply:

That’s it, you can find the source code of the project here.
Check the working diagram here.
Stay tuned, in the next part we will add handles to the rectangle so that we can manipulate it.

Leave a Reply

Your email address will not be published. Required fields are marked *