5 - Drawing Things in pyFltk

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

When Can You Draw Things in pyFltk?

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

pyFltk Drawing Functions

pyFltk provides the following types of drawing functions:

Boxes

pyFltk provides three functions that can be used to draw boxes for buttons and other UI controls. Each function uses the supplied upper-lefthand corner and width and height to determine where to draw the box.

fl_draw_box(boxtype, xpos, ypos, width, height, color);

The first box drawing function is fl_draw_box() which draws a standard boxtype c in the specified color c.

fl_frame(s, xpos, ypos, width, height);

The fl_frame() function draws a series of line segments around the given box. The string s must contain groups of 4 letters which specify one of 24 standard grayscale values, where 'A' is black and 'X' is white. The order of each set of 4 characters is: top, left, bottom, right. The results of calling fl_frame() with a string that is not a multiple of 4 characters in length are undefined.

The only difference between this function and fl_frame2() is the order of the line segments.

fl_frame2(s, xpos, ypos, width, height);

The fl_frame2() function draws a series of line segments around the given box. The string s must contain groups of 4 letters which specify one of 24 standard grayscale values, where 'A' is black and 'X' is white. The order of each set of 4 characters is: bottom, right, top, left. The results of calling fl_frame2() with a string that is not a multiple of 4 characters in length are undefined.

The only difference between this function and fl_frame() is the order of the line segments.

Clipping

You can limit all your drawing to a rectangular region by calling fl_push_clip, and put the drawings back by using fl_pop_clip. This rectangle is measured in pixels and is unaffected by the current transformation matrix.

In addition, the system may provide clipping when updating windows which may be more complex than a simple rectangle.

fl_clip(xpos, ypos, width, height)
fl_push_clip(int x, int y, int w, int h)

Intersect the current clip region with a rectangle and push this new region onto the stack. The fl_clip() name is deprecated and will be removed from future releases.

fl_push_no_clip()

Pushes an empty clip region on the stack so nothing will be clipped.

fl_pop_clip()

Restore the previous clip region.

Note:

You must call fl_pop_clip() once for every time you call fl_push_clip(). If you return to pyFltk with the clip stack not empty unpredictable results occur.

status <- fl_not_clipped(xpos, ypos, width, height)

Returns non-zero if any of the rectangle intersects the current clip region. If this returns 0 you don't have to draw the object.

Note:

Under X this returns 2 if the rectangle is partially clipped, and 1 if it is entirely inside the clip region.

(status, X, Y, W, H) <- fl_clip_box(xpos, ypos, width, height, int &X, int &Y, int &W, int &H)

Intersect the rectangle x,y,w,h with the current clip region and returns the bounding box of the result in X,Y,W,H. Returns non-zero if the resulting rectangle is different than the original. This can be used to limit the necessary drawing to a rectangle. W and H are set to zero if the rectangle is completely outside the region.

Colors

pyFltk manages colors as 32-bit unsigned integers. Values from 0 to 255 represent colors from the pyFltk 1.0.x standard colormap and are allocated as needed on screens without TrueColor support. The Fl_Color enumeration type defines the standard colors and color cube for the first 256 colors. All of these are named with symbols:

  • FL_GRAY0
  • FL_DARK1
  • FL_DARK2
  • FL_DARK3
  • FL_BACKGROUND_COLOR
  • FL_LIGHT1
  • FL_LIGHT2
  • FL_LIGHT3
  • FL_BLACK
  • FL_RED
  • FL_GREEN
  • FL_YELLOW
  • FL_BLUE
  • FL_MAGENTA
  • FL_CYAN
  • FL_DARK_RED
  • FL_DARK_GREEN
  • FL_DARK_YELLOW
  • FL_DARK_BLUE
  • FL_DARK_MAGENTA
  • FL_DARK_CYAN
  • FL_WHITE
  • Color values greater than 255 are treated as 24-bit RGB values. These are mapped to the closest color supported by the screen, either from one of the 256 colors in the pyFltk 1.0.x colormap or a direct RGB value on TrueColor screens. You can generate 24-bit RGB color values using the fl_rgb_color() function.

    fl_color(color)

    Sets the color for all subsequent drawing operations.

    For colormapped displays, a color cell will be allocated out of fl_colormap the first time you use a color. If the colormap fills up then a least-squares algorithm is used to find the closest color.

    color <- fl_color()

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

    fl_color(r, g, b)

    Set the color for all subsequent drawing operations. The closest possible match to the RGB color is used. The RGB color is used directly on TrueColor displays. For colormap visuals the nearest index in the gray ramp or color cube is used.

    Line Dashes and Thickness

    pyFltk supports drawing of lines with different styles and widths. Full functionality is not available under Windows 95, 98, and Me due to the reduced drawing functionality these operating systems provide.

    fl_line_style(style, width=0, 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 fl_line_style(0).

    Note:

    Because of how line styles are implemented on WIN32 systems, you must set the line style after setting the drawing color. If you set the color after the line style you will lose the line style settings!

    style is a bitmask which is a bitwise-OR of 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.

    Note:

    The dashes array does not work under Windows 95, 98, or Me, since those operating systems do not support complex line styles.

    Drawing Fast Shapes

    These functions are used to draw almost all the pyFltk widgets. They draw on exact pixel boundaries and are as fast as possible. Their behavior is duplicated exactly on all platforms pyFltk is ported. It is undefined whether these are affected by the transformation matrix, so you should only call these while the matrix is set to the identity matrix (the default).

    fl_point(xpos, ypos)

    Draw a single pixel at the given coordinates.

    fl_rectf(xpos, ypos, width, height)

    Color a rectangle that exactly fills the given bounding box.

    fl_rectf(xpos, ypos, width, height, r, g, b)

    Color a rectangle with "exactly" the passed r,g,b color. On screens with less than 24 bits of color this is done by drawing a solid-colored block using fl_draw_image() so that the correct color shade is produced.

    fl_rect(xpos, ypos, width, height)

    Draw a 1-pixel border inside this bounding box.

    fl_line(xpos, ypos, xpos1, ypos1)
    fl_line(xpos, ypos, xpos1, ypos1, xpos2, ypos2)

    Draw one or two lines between the given points.

    fl_loop(xpos, ypos, xpos1, ypos1, xpos2, ypos2)
    fl_loop(xpos, ypos, xpos1, ypos1, xpos2, ypos2, xpos3, ypos3)

    Outline a 3 or 4-sided polygon with lines.

    fl_polygon(xpos, ypos, xpos1, ypos1, xpos2, ypos2)
    fl_polygon(xpos, ypos, xpos1, ypos1, xpos2, ypos2, xpos3, ypos3)

    Fill a 3 or 4-sided polygon. The polygon must be convex.

    fl_xyline(xpos, ypos, xpos1)
    fl_xyline(xpos, ypos, xpos1, ypos2)
    fl_xyline(xpos, ypos, xpos1, ypos2, xpos3)

    Draw horizontal and vertical lines. A horizontal line is drawn first, then a vertical, then a horizontal.

    fl_yxline(xpos, ypos, ypos1)
    fl_yxline(xpos, ypos, ypos1, xpos2)
    fl_yxline(int x, int y, int y1, xpos2, ypos3)

    Draw vertical and horizontal lines. A vertical line is drawn first, then a horizontal, then a vertical.

    fl_arc(xpos, ypos, width, height, a1, a2)
    fl_pie(xpos, ypos, width, height, a1, a2)

    Draw ellipse sections using integer coordinates. These functions match the rather limited circle drawing code provided by X and WIN32. The advantage over using fl_arc with floating point coordinates 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.

    If a complete circle is drawn it will fit inside the passed bounding box. The two angles are measured in degrees counterclockwise from 3'oclock and are the starting and ending angle of the arc, a2 must be greater or equal to a1.

    fl_arc() draws a series of lines to approximate the arc. Notice that the integer version of fl_arc() has a different number of arguments than the fl_arc() function described later in this chapter.

    fl_pie() draws a filled-in pie slice. This slice may extend outside the line drawn by fl_arc; to avoid this use width - 1 and height - 1.

    Drawing Complex Shapes

    The complex drawing functions let you draw arbitrary shapes with 2-D linear transformations. The functionality matches that found in the Adobe® PostScriptTM language. The exact pixels that are filled are less defined than for the fast drawing functions so that pyFltk can take advantage of drawing hardware. 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.

    fl_push_matrix()
    fl_pop_matrix()

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

    fl_scale(xfraction, yfraction)
    fl_scale(xfraction)
    fl_translate(xfraction, yfraction)
    fl_rotate(dfraction)
    fl_mult_matrix(afraction, bfraction, cfraction, dfraction, xfraction, yfraction)

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

    fl_begin_line()
    fl_end_line()

    Start and end drawing lines.

    fl_begin_loop()
    fl_end_loop()

    Start and end drawing a closed sequence of lines.

    fl_begin_polygon()
    fl_end_polygon()

    Start and end drawing a convex filled polygon.

    fl_begin_complex_polygon()
    fl_gap()
    fl_end_complex_polygon()

    Start and end drawing a complex filled polygon. This polygon may be concave, may have holes in it, or may be several disconnected pieces. Call fl_gap() to seperate loops of the path. It is unnecessary but harmless to call fl_gap() before the first vertex, after the last one, or several times in a row.

    Note:

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

    fl_gap() should only be called between fl_begin_complex_polygon() and fl_end_complex_polygon(). To outline the polygon, use fl_begin_loop() and replace each fl_gap() with fl_end_loop() fl_begin_loop().

    fl_vertex(xfraction, yfraction)

    Add a single vertex to the current path.

    fl_curve(xfraction, yfraction, xfraction1, yfraction1, xfraction2, yfraction2, xfraction3, yfraction3)

    Add a series of points on a Bezier curve to the path. The curve ends (and two of the points) are at xfraction, yfraction and xfraction3, yfraction3.

    fl_arc(xpos, ypos, radius, start, end)

    Add a series of points to the current path on the arc of a circle; you can get elliptical paths by using scale and rotate before calling fl_arc(). xpos,ypos are the center of the circle, and radius is its radius. fl_arc() takes start and end angles that are measured in degrees counter-clockwise from 3 o'clock. If end is less than start then it draws the arc in a clockwise direction.

    fl_circle(xpos, ypos, radius)

    fl_circle() is equivalent to fl_arc(...,0,360) but may be faster. It must be the only thing in the path: if you want a circle as part of a complex polygon you must use fl_arc().

    Note:

    fl_circle() draws incorrectly if the transformation is both rotated and non-square scaled.

    Drawing Text

    All text is drawn in the current font. It is undefined whether this location or the characters are modified by the current transformation.

    fl_draw(string, xpos, ypos)
    fl_draw(character, n, xpos, ypos)

    Draw a nul-terminated string or an array of n characters starting at the given location. Text is aligned to the left and to the baseline of the font. To align to the bottom, subtract fl_descent() from ypos. To align to the top, subtract fl_descent() and add fl_height(). This version of fl_draw provides direct access to the text drawing function of the underlying OS. It does not apply any special handling to control characters.

    fl_draw(string, xpos, ypos, width, height, align, image = 0, draw_symbols = 1)

    Fancy string drawing function which is used to draw all the labels. The string is formatted and aligned inside the passed box. Handles '\t' and '\n', expands all other control characters to ^X, and aligns inside or against the edges of the box described by xpos, ypos, width and height. See Fl_Widget::align() for values for align. The value FL_ALIGN_INSIDE is ignored, as this function always prints inside the box.

    If image is provided and is not None, the image is drawn above or below the text as specified by the align value.

    The draw_symbols argument specifies whether or not to look for symbol names starting with the "@" character.

    The text length is limited to 1024 caracters per line.

    (width, height) <- fl_measure(string, draw_symbols = 1)

    Measure how wide and tall the string will be when printed by the fl_draw(...align) function.

    height <- fl_height()

    Recommended minimum line spacing for the current font. You can also just use the value of size passed to fl_font().

    distance <- fl_descent()

    Recommended distance above the bottom of a fl_height() tall box to draw the text at so it looks centered vertically in that box.

    width <- fl_width(string)
    width <- fl_width(string, n)
    width <- fl_width(character)

    Return the pixel width of a nul-terminated string, a sequence of n characters, or a single character in the current font.

    shortcut <- fl_shortcut_label(value)

    Unparse a shortcut value as used by Fl_Button or Fl_Menu_Item into a human-readable string like "Alt+N". This only works if the shortcut is a character key or a numbered function key. If the shortcut is zero an empty string is returned. The return value points at a static buffer that is overwritten with each call.

    Fonts

    pyFltk supports a set of standard fonts based on the Times, Helvetica/Arial, Courier, and Symbol typefaces, as well as custom fonts that your application may load. Each font is accessed by an index into a font table.

    Initially only the first 16 faces are filled in. There are symbolic names for them: FL_HELVETICA, FL_TIMES, FL_COURIER, and modifier values FL_BOLD and FL_ITALIC which can be added to these, and FL_SYMBOL and FL_ZAPF_DINGBATS. Faces greater than 255 cannot be used in Fl_Widget labels, since Fl_Widget stores the index as a byte.

    fl_font(face, size)

    Set the current font, which is then used by the routines described above. You may call this outside a draw context if necessary to call fl_width(), but on X this will open the display.

    The font is identified by a face and a size. The size of the font is measured in pixels and not "points". Lines should be spaced size pixels apart or more.

    face <- fl_font()
    size <- fl_size()

    Returns the face and size set by the most recent call to fl_font(a,b). This can be used to save/restore the font.

    Drawing Overlays

    These functions allow you to draw interactive selection rectangles without using the overlay hardware. pyFltk will XOR a single rectangle outline over a window.

    fl_overlay_rect(xpos, ypos, width, height)
    fl_overlay_clear()

    fl_overlay_rect() draws a selection rectangle, erasing any previous rectangle by XOR'ing it first. fl_overlay_clear() will erase the rectangle without drawing a new one.

    Using these functions is tricky. You should make a widget with both a handle() and draw() method. draw() should call fl_overlay_clear() before doing anything else. Your handle() method should call window().make_current() and then fl_overlay_rect() after FL_DRAG events, and should call fl_overlay_clear() after a FL_RELEASE event.

    Drawing Images

    To draw images, you can either do it directly from data in your memory, or you can create a Fl_Image object. 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. The advantage of using the object is that pyFltk will cache translated forms of the image (on X it uses a server pixmap) and thus redrawing is much faster.

    Direct Image Drawing

    The behavior when drawing images when the current transformation matrix is not the identity is not defined, so you should only draw images when the matrix is set to the identity.

    fl_draw_image(data, xpos, ypos, width, height, delta = 3, line_delta = 0)
    fl_draw_image_mono(data, xpos, ypos, width, height, delta = 1, line_delta = 0)

    Draw an 8-bit per color RGB or luminance image. The pointer points at the "r" data of the top-left pixel. Color data must be in r,g,b order. xpos, ypos are where to put the top-left corner. width and height define the size of the image. delta 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. line_delta is the delta to add to the pointer between lines (if 0 is passed it uses width * delta), and may be larger than width * delta 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:

    Gray scale (1-channel) images may be drawn. This is done if abs(delta) is less than 3, or by calling fl_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 delta greater than 1 will let you display one channel of a color image.

    Note:

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

    Image Classes

    pyFltk provides a base image class called Fl_Image which supports creating, copying, and drawing images of various kinds, along with some basic color operations. Images can be used as labels for widgets using the image() and deimage() methods or drawn directly.

    The Fl_Image class does almost nothing by itself, but is instead supported by three basic image types:

    The Fl_Bitmap class encapsulates a mono-color bitmap image. The draw() method draws the image using the current drawing color.

    The Fl_Pixmap class encapsulates a colormapped image. The draw() method draws the image using the colors in the file, and masks off any transparent colors automatically.

    The Fl_RGB_Image class encapsulates a full-color (or grayscale) image with 1 to 4 color components. Images with an even number of components are assumed to contain an alpha channel that is used for transparency. The transparency provided by the draw() method is either a 24-bit blend against the existing window contents or a "screen door" transparency mask, depending on the platform and screen color depth.

    pyFltk also provides several image classes based on the three standard image types for common file formats:

    Each of these image classes load a named file of the corresponding format. The Fl_Shared_Image class can be used to load any type of image file - the class examines the file and constructs an image of the appropriate type.

    Finally, pyFltk provides a special image class called Fl_Tiled_Image to tile another image object in the specified area. This class can be used to tile a background image in a Fl_Group widget, for example.

    copy();
    copy(width, height);

    The copy() method creates a copy of the image. The second form specifies the new size of the image - the image is resized using the nearest-neighbor algorithm.

    draw(xpos, ypos, width, height, ox = 0, oy = 0);

    The draw() method draws the image object. xpos, ypos, width, height indicates a destination rectangle. ox,oy,width,height is a source rectangle. This source rectangle is copied to the destination. The source rectangle may extend outside the image, i.e. ox and oy may be negative and width and height may be bigger than the image, and this area is left unchanged.

    draw(xpos, ypos)

    Draws the image with the upper-left corner at xpos, ypos. This is the same as doing draw(x,y,img.w(),img.h(),0,0).