QuartzTutorial03

Quartz Tutorial 3

Exploring the drawing of boxes and rectangles, points, circles and other mysterious shapes.

Rectangles and The Points that Form Them

All drawing in Quartz involves rectangles. The NSRectstruct is used to describe a rectangle’s location and dimensions:
A Rectangle – or Square for that matter – is described in the Cocoa structure NSRect. All the structures can be found here.
typedef struct {
NSPoint origin;
NSSize size;
} NSRect;

You don’t need to type this in. Remember, it’s already there in the system. But what it does mean is that you can follow this when you outline a square of your own.

// make a square beginning at (0,0) which is 20 pixels wide x 20 pixels high
// Remember, the Origin is at the bottom Left, always. This is the Anchor Point.

NSRect aSquare;

aSquare.origin.x    = 0;
aSquare.origin.y    = 0;
aSquare.size.width  = 20;
aSquare.size.height = 20;

quartz-square

The code above does not actually draw this square – it’s just a representation to visualise the code.

The origin field is the “anchor point” of the rect, where the drawing starts. A point is described by NSPoint, which has x and y coordinates:

Do you remember how we used this in Tutorial 2 to draw the coloured rectangle? In this code we set the Origin at a set of points, not at 0,0, but at a point that is x = 0 + 120, y = 0 + 120 so the origin is actually above and to the right by 120 points of the default, base origin.

// Set up the rectangle for drawing
ourRect.origin.x = ourRect.origin.y = 120.0;
ourRect.size.width = 130.0;
ourRect.size.height = 100.0;
// Draw and fill rectangle
CGContextFillRect(myContext, ourRect);

In this case, it’s the GREEN rectangle.
QuaertzTutorial02-05

 

 

typedef struct {
float x;
float y;
} NSPoint;

// make three points on the canvas

NSPoint point1;
point1.x = 4;
point1.y = 11;

NSPoint point2;
point2.x = 12;
point2.y = 21;

NSPoint point3;
point3.x = 19;
point3.y = 8;

 

You can see from the above, that I have created three different points. If you want to set them as the ORIGIN of a drawing, you have to use the word ‘origin’ as in NSRect structure. Otherwise they just remain as points. They don’t display. You use Points as places to draw lines to, or from. We will look at that in the next tutorials.

 

That’s it for this tutorial. Tutorial 4 will follow.

 

Leave a Reply

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

CAPTCHA * Time limit is exhausted. Please reload CAPTCHA.