Cairo Documentation
Cairo Documentation
Cairo Tutorial
Table of Contents
Forward – Why this Documentation?
Cairo's Drawing Model
o Nouns
o Verbs
Drawing with Cairo
o Preparing and Selecting a Source
o Creating a Path
Understanding Text
Working with Transforms
Where to Go Next
Tips and Tricks
o Line Width
o Text Alignment
Perhaps this will help you decide. As I am writing this information I am currently
incorporating this framework into a VB6 application I wrote sometime around the turn
of this century (21st). As was the case when I originally wrote the application, each
modification or feature is created ‘on-the-fly’. What that means is that when I have
something that needs to be done, I learn just enough to do it (often with the help of
others online), then move on. Well, that also happens to be the case in incorporating
this framework into a very old VB6 application.
I have spent an incredible amount of hours trying to learn how to use this framework
for my VB6 project. Reading code, the included comments when available, and doing
multiple searches online or within the vbForum, is a bit of a choppy way to learn for a
greenhorn programmer. You find yourself heavily reliant on the assistance of others,
which means a lot of waiting time. So as I accumulate the answers, why not document
it for future reference? And in the event another dummy like me comes around
needing more hand-holding, wouldn’t it be nice to have something like this around?
So why bother? Why not use the MS API and its GDI/GDI+ libs? Because I like
anything that makes my work simpler, and I am going to guess you do as well or you
would not be reading this.
Olaf Schmidt is the person behind this framework. As he has described on his website
(http://www.vbrichclient.com), “It’s main purpose is to decouple from as many MS-
COM dependencies as possible…”. There is more to it, and I invite you to visit his
website where you will also find the latest version of the RC framework.
In addition to providing a great wrapper for those interested in SQLite (years ago Olaf
provided much help in my incorporating SQLite in another app that still has users
today), he has binded the Cairo 2D graphics library originally written in the C
programming language into RC6 making it easily accessible to VB6 programmers. I
invite you to check out the Cairo site at (https://cairographics.org).
While I cannot possibly include everything that this framework can do, enough should
be included here to give a leg up. You will likely need help anyway, but if it saves you
time along the way, then it has been worth it. As for me, I may need to refresh my
brain cells on this subject, and I know I stored some of those cells here.
Cairo's Drawing Model
In order to explain the operations used by cairo, we first delve into a model
of how cairo models drawing. There are only a few concepts involved,
which are then applied over and over by the different methods. First I'll
describe the nouns: destination, source, mask, path, and context. After that I'll
describe the verbs which offer ways to manipulate the nouns and draw the
graphics you wish to create.
Nouns
Cairo's nouns are somewhat abstract. To make them concrete I'm including
diagrams that depict how they interact. The first three nouns are the three
layers in the diagrams you see in this section. The fourth noun, the path, is
drawn on the middle layer when it is relevant. The final noun, the context,
isn't shown.
Destination
The source is the "paint" you're about to work with. I show this as it is—
plain black for several examples—but translucent to show lower layers.
Unlike real paint, it doesn't have to be a single color; it can be a pattern or
even a previously created destination surface (see How do I paint from one
surface to another?). Also unlike real paint it can contain transparency
information—the Alpha channel.
Mask
The mask is the most important piece: it controls where you apply the
source to the destination. I will show it as a yellow layer with holes where it
lets the source through. When you apply a drawing verb, it's like you stamp
the source to the destination. Anywhere the mask allows, the source is
copied. Anywhere the mask disallows, nothing happens.
Path
The path is somewhere between part of the mask and part of the context. I
will show it as thin green lines on the mask layer. It is manipulated by path
verbs, then used by drawing verbs.
Context
The context keeps track of everything that verbs affect. It tracks one source,
one destination, and one mask. It also tracks several helper variables like
your line width and style, your font face and size, and more. Most
importantly it tracks the path, which is turned into a mask by drawing verbs.
Before you can start to draw something with cairo, you need to create the
context. When you create a cairo context, it must be tied to a specific
surface—for example, an image surface if you want to create a PNG file.
You can initialize your cairo context like this:
Surfaces
ImageSurface — Rendering to memory buffers
PDFSurface — Rendering PDF documents
PSSurface — Rendering PostScript documents
SVGSurface — Rendering SVG documents
DXSurface32Bit -
Verbs
The reason you are using cairo in a program is to draw. Cairo internally
draws with one fundamental drawing operation: the source and mask are
freely placed somewhere over the destination. Then the layers are all
pressed together and the paint from the source is transferred to the
destination wherever the mask allows it. To that extent the following five
drawing verbs, or operations, are all similar. They differ by how they
construct the mask.
Stroke
The context .Stroke operation takes a virtual pen along the path. It allows
the source to transfer through the mask in a thin (or thick) line around the
path, according to the pen's line width, dash style, and line caps.
Fill
The context .Fill operation instead uses the path like the lines of a coloring
book, and allows the source through the mask within the hole whose
boundaries are the path. For complex paths (paths with multiple closed sub-
paths—like a donut—or paths that self-intersect) this is influenced by
the fill rule. Note that while stroking the path transfers the source for half of
the line width on each side of the path, filling a path fills directly up to the
edge of the path and no further.
The following code does not expose the full power of the Mask routines
available, but is a simple demonstration. Another routine (not shown) is
MaskSurface(Pattern As cCairoPattern, [srfX as Double], [srfY as Double]).
int i, j;
cairo_pattern_t *radpat, *linpat;
Creating a Path
Cairo always has an active path. If you call cairo_stroke() it will draw the
path with your line settings. If you call cairo_fill() it will fill the inside of
the path. But as often as not, the path is empty, and both calls will result in
no change to your destination. Why is it empty so often? For one, it starts
that way; but more importantly after each cairo_stroke() or cairo_fill() it
is emptied again to let you start building your next path.
What if you want to do multiple things with the same path? For instance to
draw a red rectangle with a black border, you would want to fill the
rectangle path with a red source, then stroke the same path with a black
source. A rectangle path is easy to create multiple times, but a lot of paths
are more complex.
Straight Lines
Arcs are parts of the outside of a circle. Unlike straight lines, the point you
directly specify is not on the path. Instead it is the center of the circle that
makes up the addition to the path. Both a starting and ending point on the
circle must be specified, and these points are connected either clockwise
by cairo_arc() or counter-clockwise by cairo_arc_negative(). If the
previous reference point is not on this new curve, a straight line is added
from it to where the arc begins. The reference point is then updated to
where the arc ends. There are only absolute versions.
Curves
Curves in cairo are cubic Bézier splines. They start at the current reference
point and smoothly follow the direction of two other points (without going
through them) to get to a third specified point. Like lines, there are both
absolute (cairo_curve_to()) and relative (cairo_rel_curve_to()) versions.
Note that the relative variant specifies all points relative to the previous
reference point, rather than each relative to the preceding control point of
the curve.
cairo_close_path (cr);
Text
Finally text can be turned into a path with cairo_text_path(). Paths created
from text are like any other path, supporting stroke or fill operations. This
path is placed anchored to the current reference point,
so cairo_move_to() your desired location before turning text into a path.
However there are performance concerns to doing this if you are working
with a lot of text; when possible you should prefer using the
verb cairo_show_text() over cairo_text_path() and cairo_fill().
Understanding Text
To use text effectively you need to know where it will go. The
methods cairo_font_extents() and cairo_text_extents() get you this
information. Since this diagram is hard to see so small, I suggest getting
its source and bump the size up to 600. It shows the relation between the
reference point (red dot); suggested next reference point (blue dot);
bounding box (dashed blue lines); bearing displacement (solid blue line);
and height, ascent, baseline, and descent lines (dashed green).
The reference point is always on the baseline. The descent line is below
that, and reflects a rough bounding box for all characters in the font.
However it is an artistic choice intended to indicate alignment rather than a
true bounding box. The same is true for the ascent line above. Next above
that is the height line, the artist-recommended spacing between subsequent
baselines. All three of these are reported as distances from the baseline, and
expected to be positive despite their differing directions.
The bearing is the displacement from the reference point to the upper-left
corner of the bounding box. It is often zero or a small positive value for x
displacement, but can be negative x for characters like j as shown; it's
almost always a negative value for y displacement. The width and height
then describe the size of the bounding box. The advance takes you to the
suggested reference point for the next letter. Note that bounding boxes for
subsequent blocks of text can overlap if the bearing is negative, or the
advance is smaller than the width would suggest.
In addition to placement, you also need to specify a face, style, and size. Set
the face and style together with cairo_select_font_face(), and the size
with cairo_set_font_size(). If you need even finer control, try getting
a cairo_font_options_t with cairo_get_font_options(), tweaking it, and
setting it with cairo_set_font_options().
Working with Transforms
Transforms have three major uses. First they allow you to set up a
coordinate system that's easy to think in and work in, yet have the output be
of any size. Second they allow you to make helper functions that work at or
around a (0, 0) but can be applied anywhere in the output image. Thirdly
they let you deform the image, turning a circular arc into an elliptical arc,
etc. Transforms are a way of setting up a relation between two coordinate
systems. The device-space coordinate system is tied to the surface, and
cannot change. The user-space coordinate system matches that space by
default, but can be changed for the above reasons. The helper
functions cairo_user_to_device() and cairo_user_to_device_distance() te
ll you what the device-coordinates are for a user-coordinates position or
distance.
Correspondingly cairo_device_to_user() and cairo_device_to_user_dista
nce() tell you user-coordinates for a device-coordinates position or distance.
Remember to send positions through the non-distance variant, and relative
moves or other distances through the distance variant.
Use the first when relevant because it is often the most readable; use the
third when necessary to access additional control not available with the
primary functions.
Be careful when trying to draw lines while under transform. Even if you set
your line width while the scale factor was 1, the line width setting is always
in user-coordinates and isn't modified by setting the scale. While you're
operating under a scale, the width of your line is multiplied by that scale. To
specify a width of a line in pixels, use cairo_device_to_user_distance() to
turn a (1, 1) device-space distance into, for example, a (0.01, 0.01) user-
space distance. Note that if your transform deforms the image there isn't
necessarily a way to specify a line with a uniform width.
Where to Go Next
This wraps up the tutorial. It doesn't cover all functions in cairo, so for some
"advanced" lesser-used features, you'll need to look elsewhere. The code
behind the examples (layer diagrams, drawing illustrations) uses a handful
of techniques that aren't described within, so analyzing them may be a good
first step. Other examples on cairographics.org lead in different directions.
As with everything, there's a large gap between knowing the rules of the
tool, and being able to use it well. The final section of this document
provides some ideas to help you traverse parts of the gap.
When you're working under a deforming scale, you may wish to still have
line widths that are uniform in device space. For this you should return to a
uniform scale before you stroke the path. In the image, the arc on the left is
stroked under a deformation, while the arc on the right is stroked under a
uniform scale.
cairo_save (cr);
cairo_scale (cr, 0.5, 1);
cairo_arc (cr, 0.5, 0.5, 0.40, 0, 2 * M_PI);
cairo_stroke (cr);
Text Alignment
When you try to center text letter by letter at various locations, you have to
decide how you want to center it. For example the following code will
actually center letters individually, leading to poor results when your letters
are of different sizes. (Unlike most examples, here I assume a 26 x 1
workspace.)
cairo_text_extents_t te;
char alphabet[] = "AbCdEfGhIjKlMnOpQrStUvWxYz";
char letter[2];
Instead the vertical centering must be based on the general size of the font,
thus keeping your baseline steady. Note that the exact positioning now
depends on the metrics provided by the font itself, so the results are not
necessarily the same from font to font.
cairo_font_extents_t fe;
cairo_text_extents_t te;
char alphabet[] = "AbCdEfGhIjKlMnOpQrStUvWxYz";
char letter[2];