Drawing Things in FLTK

This chapter covers the drawing functions that are provided with FLTK.

When Can You Draw Things in FLTK?

There are only certain places you can execute drawing code in FLTK. Calling these functions at other places will result in undefined behavior!

FLTK Drawing Functions

To use the drawing functions you must first include the <fltk/draw.h> header file. FLTK provides the following types of drawing functions:

Current Transformation

FLTK provides an arbitrary 2-D linear transformation (ie rotation, scale, skew, reflections, and translation). This is very similar to PostScript, PDF, and SVG.

Due to limited graphics capabilities of some systems, all drawing methods that take 4 integer values (defining a box) only transform the x and y values, and round them to the nearest integer. You should use functions that take floating-point coordinates if you want accurately scaled drawings.

void fltk::push_matrix()
void fltk::pop_matrix()

Save and restore the current transformation. The maximum depth of the stack is 10.

void fltk::scale(float factor_x, float factor_y)
void fltk::scale(float factor)

void fltk::translate(float dx, float dy)
void fltk::translate(int dx, int dy)
void fltk::rotate(float degrees_ccw)
void fltk::mult_matrix(float a, float b, float c, float d, float x, float y)

Concatenate another transformation onto the current one. The rotation angle is in degrees (not radians) and is counter-clockwise.

fltk::translate(int,int) is provided because it is much faster than the floating-point version. However C++ will not "resolve" which one you want to call if you try passing doubles as arguments. To get it to compile, make sure you cast the arguments to float (add 'f' after floating-point constants). Use the 'f' versions (ie sinf(), cosf(), etc) of the math functions from <fltk/math.h> to produce floats and get maximum calculation speed.

void fltk::load_identity()

Replace the current transform with the identity transform, which puts 0,0 in the top-left corner of the window and each unit is 1 pixel in size.

void fltk::transform(float& x, float& y)

Replace x and y with the transformed coordinates.

void fltk::transform(int& x, int& y)

Replace x and y with the transformed coordinates, rounded to the nearest integer.

void fltk::transform_distance(float& x, float& y)

Replace x and y with the tranformed coordinates, ignoring translation. This transforms a vector which is measuring a distance between two positions, rather than a position.

Clipping

You can limit all your drawing to a region by calling fltk::push_clip(), and put the drawings back by using fltk::pop_clip(). Fltk may also set up clipping before draw() is called to limit the drawing to the region of the window that is damaged.

When drawing you can also test the current clip region with fltk::not_clipped() and fltk::clip_box(). By using these to skip over complex drawings that are clipped you can greatly speed up your program's redisplay.

Notice that the width and height of the clipping region is measured in transformed coordianates.

void fltk::push_clip(int x, int y, int w, int h)

Pushes the intersection of the current region and this rectangle onto the clip stack.

void fltk::clip_out(int x, int y, int w, int h)

Remove the rectangle from the current clip region, thus making it a more complex shape. This does not push the stack, it just replaces the top of it. This does not work on X or Win32 unless fltk::push_clip() has been called at least once.

void fltk::push_no_clip()

Pushes an empty clip region on the stack so nothing will be clipped. This lets you draw outside the current clip region. You should not use this :-)

void fltk::pop_clip()

Restore the previous clip region. You must call fltk::pop_clip() exactly once for every time you call fltk::clip(). If you return to FLTK with the clip stack not empty unpredictable results occur.

int fltk::not_clipped(int x, int y, int w, int h)

Return non-zero if the intersection of the rectangle and the current clip region is non-zero. If this returns zero you don't have to draw anything in that rectangle. Under X this returns 1 if the interesection is equal to the rectangle, and 2 if the intersection is only part of the rectangle.

int fltk::clip_box(int x, int y, int w, int h, int& X, int& Y, int& W, int& H)

Find the smallest rectangle that surrounds the intersection of the rectangle x,y,w,h with the current clip region. This "bounding box" is returned in X,Y,W,H. The return value is non-zero if the bounding box is different than the rectangle. If the intersection is empty then W and H are set to zero.

This can be used to limit complex pixel operations (like drawing images) to the smallest rectangle needed to update the visible area.

Colors

void fltk::color(fltk::Color)

Set the color for all subsequent drawing operations. fltk::Color is a typedef for a 32-bit integer containing r,g,b bytes and an "index" byte. The index is used if r,g,b is zero. For instance 0xFF008000 is 255 red, zero green, and 128 blue.

(On non-TrueColor X displays fltk rounds the desired color to the nearest color in a small (200) set of colors and allocates that from X to avoid consuming the entire colormap. On Windows colormapped displays the system dithering is used for all colors, which looks lousy, but Windows does not have the defective X behavior and thus you usually are not forced to set the screen to 8-bit mode)

fltk::Color fltk::color()

Returns the last fltk::color() that was set. This can be used for state save/restore.

Line dashes and thickness

void fltk::line_style(int style, int width=0, char* dashes=0)

Set how to draw lines (the "pen"). If you change this it is your responsibility to set it back to the default with fltk::line_style(0).

style is a bitmask in which you 'or' the following values. If you don't specify a dash type you will get a solid line. If you don't specify a cap or join type you will get a system-defined default of whatever value is fastest.

width is the number of pixels thick to draw the lines. Zero results in the system-defined default, which on both X and Windows is somewhat different and nicer than 1.

dashes is a pointer to an array of dash lengths, measured in pixels. The first location is how long to draw a solid portion, the next is how long to draw the gap, then the solid, etc. It is terminated with a zero-length entry. A null pointer or a zero-length array results in a solid line. Odd array sizes are not supported and result in undefined behavior. The dashes array does not work on Windows 95/98, use the dash styles instead.

Path construction and drawing

These functions let you draw arbitrary shapes with 2-D linear transformations. The functionality matches that found in Adobe® PostScriptTM. On both X and WIN32 the transformed vertices are rounded to integers before drawing the line segments: this severely limits the accuracy of these functions for complex graphics, so use OpenGL when greater accuracy and/or performance is required.

void fltk::newpath()

Clear the current "path". This is normally done by fltk::fill() or any other drawing command.

void fltk::vertex(float x, float y)
void fltk::vertex(int x, int y)

Add a single vertex to the current path. (If you are familiar with PostScript, this does a "moveto" if the path is clear or fltk::closepath was done last, otherwise it does a "lineto").

fltk::vertex(int,int) is provided because it is much faster than the floating-point version. However C++ will not "resolve" which one you want to call if you try passing doubles as arguments. To get it to compile, make sure you cast the arguments to float (add 'f' after floating-point constants). Use the 'f' versions (ie sinf(), cosf(), etc) of the math functions from <fltk/math.h> to produce floats and get maximum calculation speed.

void fltk::vertices(int n, const float v[][2]);
void fltk::vertices(int n, const int v[][2]);

Add a whole set of vertices to the current path. This is much faster than calling fltk::vertex once for each point.

void fltk::transformed_vertices(int n, const float v[][2]);

Add a set of vertices to the current path where the coordinates are in the units returned by fltk::transform(). This is used by fltk::curve() and can be used by other code to calculate shapes.

void fltk::closepath();

Similar to drawing another vertex back at the starting point, but fltk knows the path is closed. The next fltk::vertex will start a new disconnected part of the shape.

It is harmless to call fltk::closepath() several times in a row, or to call it before the first point. Sections with less than 3 points in them will not draw anything when filled.

void fltk::curve(float x, float y, float x1, float y1, float x2, float y2, float x3, float y3)

Add a series of points on a Bezier curve to the path. The curve ends (and two of the points) are at x,y and x3,y3.

void fltk::arc(float x, float y, float w, float h, float start, float end)

Add a series of points to the current path on the arc of an ellipse. The ellipse in inscribed in the x,y,w,h rectangle, and the start and end angles are measured in degrees counter-clockwise from 3 o'clock, 45 points at the upper-right corner of the rectangle. If end is less than start then it draws the arc in a clockwise direction.

void fltk::ellipse(float x, float y, float w, float h)

Does closepath() and then adds a series of points on the edge of an ellipse inscribed in the given rectangle, then another closepath().

This tries to take advantage of the primitive drawing provided by X and Win32, which means it only draws the right thing if the rotation is a multiple of 90 degrees, or if the shape is a circle. Currently there can only be one ellipse or circle in a path.

void fltk::circle(float x, float y, float r)

fltk::circle() draws a circle of radius r centered on the point x,y. The result is always a circle, irregardless of scale. This also tries to take advantage of the X/Win32 graphics primitives like fltk::ellipse.

void fltk::points()

Draw a point (one pixel) for every vertex in the path, then clear the path.

void fltk::stroke()

Draw a line between all the points in the path (see fltk::line_type() for ways to set the thicknesss and dot pattern of the line), then clear the path.

void fltk::fill()

Does fltk::closepath() and then fill with the current color, and then clear the path.

For portability, you should only draw polygons that appear the same whether "even/odd" or "non-zero" winding rules are used to fill them. This mostly means that holes should be drawn in the opposite direction of the outside.

void fltk::fill_stroke(fltk::Color linecolor)

Does fltk::fill(), then sets the current color to linecolor and does fltk::stroke with the same closed path, and then clears the path.

Drawing that bypasses the path mechanism

These graphics will go directly to the primitives provided by X or GDI. Only the x,y coordinates are transformed and in most cases they are rounded to the nearest integer.

void fltk::rect(int x, int y, int w, int h)

Draw a line inside this bounding box (currently correct only for 0-thickness lines).

void fltk::rectf(int x, int y, int w, int h)

Color a rectangle that exactly fills the given bounding box.

void fltk::line(int x, int y, int x1, int y1)

Draw a straight line between the two points.

void fltk::pie(int x, int y, int w, int h, float start, float end, int what=FL_PIE);

These functions match the rather limited circle drawing code provided by X and WIN32. The advantage over using fltk::arc is that they are faster because they often use the hardware, and they draw much nicer small circles, since the small sizes are often hard-coded bitmaps. Only the integer translation of the current transformation is obeyed on most systems.

The allowed types are:

Text

See fltk::Font for a description of what can be passed as a font. For most uses one of the built-in constant fonts like fltk::HELVETICA can be used.

void fltk::font(fltk::Font, float size)

Set the current font and font scaling so the size is size pixels. The size is unaffected by the current transformation matrix (you may be able to use fltk::transform() to get the size to get a properly scaled font).

The size is given in pixels. Many pieces of software express sizes in "points" (for mysterious reasons, since everything else is measured in pixels!). To convert these point sizes to pixel sizes use the following code:

const fltk::Screen_Info& info = fltk::info();
float pixels_per_point = info.height/(info.height_mm*(72/25.4));
float font_pixel_size = font_point_size*pixels_per_point;

void fltk::font(const char* name, float size);
void fltk::font(const char* name, int attributes, float size);

Set the current font by name. Exactly what names work depend on your system, it is best to use fltk::list_fonts to see what is provided. See fltk::find_font for how the name and attributes are interpreted.

void fltk::encoding(const char*);

The encoding determines how the bytes sent to fltk::draw are turned into glyphs. If the current font cannot do the encoding, some default encoding will be used (for instance the Symbol font always works without having to set the encoding).

In current implementations you must call fltk::font(...) after this for the change in encoding to take effect.

The only way to find out what encodings are going to work is to call fltk::Font::encodings().

In general you should set this on startup to your locale, and leave it alone. We hope to support UTF-8 encoding by default in fltk in the future. It is likely that when this happens support for fltk::encoding() will be removed.

The default is "iso8859-1"

fltk::Font fltk::font()

Returns the current font.

float fltk::size()

Returns the current font size.

const char* fltk::encoding();

Returns the current encoding.

float fltk::height()

Returns the vertical size of the font according to the system. I recommended that you use fltk::size() instead for portability and because many X fonts return erroneous values for this. Notice that the dimension is in transformed coordinates.

float fltk::descent()

Recommended distance above the bottom of a fltk::height() tall box to draw the text at so it looks centered vertically in that box. Notice that the dimension is in transformed coordinates.

float fltk::width(const char*)
float fltk::width(const char*, int n)

Return the pixel width of a nul-terminated string, or a string of length n bytes. Notice that the dimension is in transformed coordinates.

void fltk::draw(const char*, float x, float y)
void fltk::draw(const char*, int n, float x, float y)

Draw a nul-terminated string or an array of n bytes starting at the given location.

void fltk::transformed_draw(const char*, int n, float x, float y)

Draw an array of n bytes starting at the given location, which is given in actual device units, such as those returned by fltk::transform(). You must use this if you wish to accurately append pieces of text together.

void fltk::draw(const char*, int x, int y, int w, int h, fltk::Flags)

Fancy string drawing function which is used to draw all the labels. The string is formatted and aligned inside the passed box (only the x/y are transformed, the width and height are in device units). Handles '\t' and '\n', expands all other control characters to ^X, and aligns inside or against the edges of the box. See fltk::Labeltype_::draw() for values for the flags (fltk::ALIGN_INSIDE is ignored, it acts like it is always on).

void fltk::measure(const char*, int& w, int& h)

Measure how wide and tall the string will be when printed by the fltk::draw(...align) function. If the incoming w is non-zero it will wrap to that width. Notice that the dimensions are in transformed coordinates.

Images

If you plan to draw the same image many times, you may want an fltk::Image subclass such as fltk::Bitmap, fltk::RGB_Image, or fltk::Pixmap and call draw() on them. The advantage of using the object is that FLTK will cache translated forms of the image (on X it uses a server pixmap) and thus redrawing is much faster. In addition, on current systems, fltk::Image is the only way to get transparency or to draw 1-bit bitmaps.

The advantage of drawing directly is that it is more intuitive, and it is faster if the image data changes more often than it is redrawn.

Currently the image is only affected by the integer portion of the current transformation. This may change in future versions!

void fltk::draw_image(const uchar*, int X, int Y, int W, int H, int D = 3, int LD = 0)
void fltk::draw_image_mono(const uchar*, int X, int Y, int W, int H, int D = 1, int LD = 0)

Draw an 8-bit per color RGB or luminance image. The pointer points at the byte of red data of the top-left pixel. Data must be in r,g,b order. X,Y are where to put the top-left corner. W and H define the size of the image. D is the delta to add to the pointer between pixels, it may be any value greater or equal to 3, or it can be negative to flip the image horizontally. LD is the delta to add to the pointer between lines (if 0 is passed it uses W * D), and may be larger than W * D to crop data, or negative to flip the image vertically.

It is highly recommended that you put the following code before the first show() of any window in your program to get rid of the dithering if possible:

fltk::visual(fltk::RGB);
Gray scale (1-channel) images may be drawn. This is done if abs(D) is less than 3, or by calling fltk::draw_image_mono(). Only one 8-bit sample is used for each pixel, and on screens with different numbers of bits for red, green, and blue only gray colors are used. Setting D greater than 1 will let you display one channel of a color image.

The X version does not support all possible visuals. If FLTK cannot draw the image in the current visual it will abort. FLTK supports any visual of 8 bits or less, and all common TrueColor visuals up to 32 bits.

typedef void (*fltk::draw_image_cb)(void*, int x, int y, int w, uchar *)
void fltk::draw_image(fltk::draw_image_cb, void*, int X, int Y, int W, int H, int D = 3)
void fltk::draw_image_mono(fltk::draw_image_cb, void*, int X, int Y, int W, int H, int D = 1)

Call the passed function to provide each scan line of the image. This lets you generate the image as it is being drawn, or do arbitrary decompression of stored data (provided it can be decompressed to individual scan lines easily).

The callback is called with the void* user data pointer (this can be used to point at a structure of information about the image), and the x, y, and w of the scan line desired from the image. 0,0 is the upper-left corner (not X,Y ). A pointer to a buffer to put the data into is passed. You must copy w pixels from scanline y, starting at pixel x , to this buffer.

Due to cropping, less than the whole image may be requested. So x may be greater than zero, the first y may be greater than zero, and w may be less than W. The buffer is long enough to store the entire W * D pixels, this is for convienence with some decompression schemes where you must decompress the entire line at once: decompress it into the buffer, and then if x is not zero, copy the data over so the x'th pixel is at the start of the buffer.

You can assume the y's will be consecutive, except the first one may be greater than zero.

If D is 4 or more, you must fill in the unused bytes with zero.