Drawing Tools
Drawing code in wxWidgets operates like a very fast artist, rapidly
selecting colors and drawing tools, drawing a little part of the scene,
then selecting different tools, drawing another part of the scene, and
so on. Here we describe the wxColour, wxPen, wxBrush, wxFont and
wxPalette classes. You will also find it useful to refer to the
descriptions of other classes relevant to drawing—wxRect, wxRegion, wxPoint, and wxSize, which are described in Chapter 13, "Data Structure Classes."
Note that these classes use "reference-counting," efficiently
copying only internal pointers rather than chunks of memory. In most
circumstances, you can create color, pen, brush, and font objects on
the stack as they are needed without worrying about speed implications.
If your application does have performance problems, you can take steps
to improve efficiency, such as storing some objects as data members.
wxColour
You use wxColour to define various aspects of color when drawing. (Because wxWidgets started life in Edinburgh, the API uses British spelling. However, to cater for the spelling sensibilities of the New World, wxWidgets defines wxColor as an alias for wxColour.)
You can specify the text foreground and background color for a device context using a device context's SetTextForeground and SetTextBackground functions, and you also use wxColour to create pens and brushes.
A wxColour object can be constructed in a number of
different ways. You can pass red, green, and blue values (each 0 to
255), or a standard color string such as WHITE or CYAN, or you can create it from another wxColour object. Alternatively, you can use the stock color objects, which are pointers: wxBLACK, wxWHITE, wxRED, wxBLUE, wxGREEN, wxCYAN, and wxLIGHT_GREY. The stock object wxNullColour is an uninitialized color for which the Ok function always returns false.
Using the wxSystemSettings class, you can retrieve some
standard, system-wide colors, such as the standard 3D surface color,
the default window background color, menu text color, and so on. Please
refer to the documentation for wxSystemSettings::GetColour for the identifiers you can pass.
Here are some different ways to create a wxColour object:
wxColour color(0, 255, 0); // green
wxColour color(wxT("RED")); // red
// The color used for 3D faces and panels
wxColour color(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE));
You can also use the wxTheColourDatabase pointer to add a new color, find a wxColour object for a given name, or find the name corresponding to the given color:
wxTheColourDatabase->Add(wxT("PINKISH"), wxColour(234, 184, 184));
wxString name = wxTheColourDatabase->FindName(
wxColour(234, 184, 184));
wxString color = wxTheColourDatabase->Find(name);
These are the available standard colors: aquamarine, black, blue,
blue violet, brown, cadet blue, coral, cornflower blue, cyan, dark
gray, dark green, dark olive green, dark orchid, dark slate blue, dark
slate gray dark turquoise, dim gray, firebrick, forest green, gold,
goldenrod, gray, green, green yellow, indian red, khaki, light blue,
light gray, light steel blue, lime green, magenta, maroon, medium
aquamarine, medium blue, medium forest green, medium goldenrod, medium
orchid, medium sea green, medium slate blue, medium spring green,
medium turquoise, medium violet red, midnight blue, navy, orange,
orange red, orchid, pale green, pink, plum, purple, red, salmon, sea
green, sienna, sky blue, slate blue, spring green, steel blue, tan,
thistle, turquoise, violet, violet red, wheat, white, yellow, and
yellow green.
wxPen
You define the current pen for the device context by passing a wxPen object to SetPen. The current pen defines the outline color, width, and style for subsequent drawing operations. wxPen has a low overhead, so you can create instances on the stack within your drawing code rather than storing them.
As well as a color and a width, a pen has a style, as described in
Table 5-2. Hatch and stipple styles are not supported by the GTK+ port.
Table 5-2. wxPen Styles
Style
|
Example
|
Description
|
wxSOLID
|
|
Lines are drawn solid.
|
wxTRANSPARENT
|
|
Used when no pen drawing is desired.
|
wxDOT
|
|
The line is drawn dotted.
|
wxLONG_DASH
|
|
Draws with a long dashed style.
|
wxSHORT_DASH
|
|
Draws with a short dashed style. On Windows, this is the same as wxLONG_SASH.
|
wxDOT_DASH
|
|
Draws with a dot and a dash.
|
wxSTIPPLE
|
|
Uses a stipple bitmap, which is passed as the first constructor argument.
|
wxUSER_DASH
|
|
Uses user-specified dashes. See the reference manual for further information.
|
wxBDIAGONAL_HATCH
|
|
Draws with a backward-diagonal hatch.
|
wxCROSSDIAG_HATCH
|
|
Draws with a cross-diagonal hatch.
|
wxFDIAGONAL_HATCH
|
|
Draws with a forward-diagonal hatch.
|
wxCROSS_HATCH
|
|
Draws with a cross hatch.
|
wxHORIZONTAL_HATCH
|
|
Draws with a horizontal hatch.
|
wxVERTICAL_HATCH
|
|
Draws with a vertical hatch.
|
Call SetCap if you need to specify how the ends of thick lines should look: wxCAP_ROUND (the default) specifies rounded ends, wxCAP_PROJECTING specifies a square projection on either end, and wxCAP_BUTT specifies that the ends should be square and should not project.
You can call SetJoin to set the appearance where lines join. The default is wxJOIN_ROUND, where the corners are rounded. Other values are wxJOIN_BEVEL and wxJOIN_MITER.
There are some stock pens that you can use: wxRED_PEN, wxCYAN_PEN, wxGREEN_PEN, wxBLACK_PEN, wxWHITE_PEN, wxTRANSPARENT_PEN, wxBLACK_DASHED_PEN, wxGREY_PEN, wxMEDIUM_GREY_PEN, and wxLIGHT_GREY_PEN. These are pointers, so you'll need to dereference them when passing them to SetPen. There is also the object wxNullPen (an object, not a pointer), an uninitialized pen object that can be used to reset the pen in a device context.
Here are some examples of creating pens:
// A solid red pen
wxPen pen(wxColour(255, 0, 0), 1, wxSOLID);
wxPen pen(wxT("RED"), 1, wxSOLID);
wxPen pen = (*wxRED_PEN);
wxPen pen(*wxRED_PEN);
The last two examples use reference counting, so pen's internal data points to wxRED_PEN's
data. Reference counting is used for all drawing objects, and it makes
the assignment operator and copy constructor cheap operations, but it
does mean that sometimes changes in one object affect the properties of
another.
One way to reduce the amount of construction and destruction of pen
objects without storing pen objects in your own classes is to use the
global pointer wxThePenList to create and store the pens you need, for example:
wxPen* pen = wxThePenList->FindOrCreatePen(*wxRED, 1, wxSOLID);
The pen object will be stored in wxThePenList and cleaned
up on application exit. Obviously, you should take care not to use this
indiscriminately to avoid filling up memory with pen objects, and you
also need to be aware of the reference counting issue mentioned
previously. You can remove a pen from the list without deleting it by
using RemovePen.
wxBrush
The current brush, specified with SetBrush, defines the fill color and style for drawing operations. You also specify the device context background color using a wxBrush, rather than with just a color. As with wxPen, wxBrush has a low overhead and can be created on the stack.
Pass a color and a style to the brush constructor. The style can be one of the values listed in Table 5-3.
Table 5-3. wxBrush Styles
Style
|
Example
|
Description
|
wxSOLID
|
|
Solid color is used.
|
wxTRANSPARENT
|
|
Used when no filling is desired.
|
wxBDIAGONAL_HATCH
|
|
Draws with a backward-diagonal hatch.
|
wxCROSSDIAG_HATCH
|
|
Draws with a cross-diagonal hatch.
|
wxFDIAGONAL_HATCH
|
|
Draws with a forward-diagonal hatch.
|
wxCROSS_HATCH
|
|
Draws with a cross hatch.
|
wxHORIZONTAL_HATCH
|
|
Draws with a horizontal hatch.
|
wxVERTICAL_HATCH
|
|
Draws with a vertical hatch.
|
wxSTIPPLE
|
|
Uses a stipple bitmap, which is passed as the first constructor argument.
|
You can use the following stock brushes: wxBLUE_BRUSH, wxGREEN_BRUSH, wxWHITE BRUSH, wxBLACK_BRUSH, wxGREY_BRUSH, wxMEDIUM_GREY_BRUSH, wxLIGHT_GREY_BRUSH, wxTRANSPARENT_BRUSH, wxCYAN_BRUSH, and wxRED_BRUSH. These are pointers. You can also use the wxNullBrush object (an uninitialized brush object).
Here are some examples of creating brushes:
// A solid red brush
wxBrush brush(wxColour(255, 0, 0), wxSOLID);
wxBrush brush(wxT("RED"), wxSOLID);
wxBrush brush = (*wxRED_BRUSH); // a cheap operation
wxBrush brush(*wxRED_BRUSH);
As with wxPen, wxBrush also has an associated list, wxTheBrushList, which you can use to cache brush objects:
wxBrush* brush = wxTheBrushList->FindOrCreateBrush(*wxBLUE, wxSOLID);
Use this with care to avoid proliferation of brush objects and side
effects from reference counting. You can remove a brush from the list
without deleting it by using RemoveBrush.
wxFont
You use font objects for specifying how text will appear when drawn on a device context. A font has the following properties:
The point size specifies the maximum height of the text in
points (1/72 of an inch). wxWidgets will choose the closest match it
can if the platform is not using scalable fonts.
The font family specifies one of a small number of family
names, as described in Table 5-4. Specifying a family instead of an
actual face name makes applications be more portable because you can't
usually rely on a particular typeface being available on all platforms.
Table 5-4. Font Family Identifiers
Identifier
|
Example
|
Description
|
wxFONTFAMILY_SWISS
|
|
A sans-serif font—often Helvetica or Arial depending on platform.
|
wxFONTFAMILY_ROMAN
|
|
A formal, serif font.
|
wxFONTFAMILY_SCRIPT
|
|
A handwriting font.
|
wxFONTFAMILY_MODERN
|
|
A fixed pitch font, often Courier.
|
wxFONTFAMILY_DECORATIVE
|
|
A decorative font.
|
wxFONTFAMILY_DEFAULT
|
|
wxWidgets chooses a default family.
|
The style can be wxNORMAL, wxSLANT, or wxITALIC. wxSLANT may not be implemented for all platforms and fonts.
The weight is one of wxNORMAL, wxLIGHT, or wxBOLD.
A font's underline can be on (true) or off (false).
The face name is optional and specifies a particular typeface. If empty, a default typeface will be chosen from the family specification.
The optional encoding specifies the mapping between the
character codes used in the program and the letters that are drawn onto
the device context. Please see Chapter 16, "Writing International
Applications," for more on this topic.
You can create a font with the default constructor or by specifying the properties listed in Table 5-4.
There are some stock font objects that you can use: wxNORMAL_FONT, wxSMALL_FONT, wxITALIC_FONT, and wxSWISS_FONT. These have the size of the standard system font (wxSYS_DEFAULT_GUI_FONT), apart from wxSMALL_FONT, which is two points smaller. You can also use wxSystemSettings::GetFont to retrieve standard fonts.
To use a font object, pass it to wxDC::SetFont before performing text operations, in particular DrawText and GetTextExtent.
Here are some examples of font creation.
wxFont font(12, wxFONTFAMILY_ROMAN, wxITALIC, wxBOLD, false);
wxFont font(10, wxFONTFAMILY_SWISS, wxNORMAL, wxBOLD, true,
wxT("Arial"), wxFONTENCODING_ISO8859_1));
wxFont font(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));
wxFont has an associated list, wxTheFontList, which you can use to find a previously created font or add a new one:
wxFont* font = wxTheFontList->FindOrCreateFont(12, wxSWISS,
wxNORMAL, wxNORMAL);
As with the pen and brush lists, use this with moderation because
the fonts will be deleted only when the application exits. You can
remove a font from the list without deleting it by using RemoveFont.
We'll see some examples of working with text and fonts later in the chapter. Also, you may like to play with the font demo in samples/font. It lets you set a font to see how some text will appear, and you can change the font size and other properties.
wxPalette
A palette is a table, often with a size of 256, that maps index
values to the red, green, and blue values of the display colors. It's
normally used when the display has a very limited number of colors that
need to be shared between applications. By setting a palette for a
client device context, an application's color needs can be balanced
with the needs of other applications. It is also used to map the colors
of a low-depth bitmap to the available colors, and so wxBitmap has an optional associated wxPalette object.
Because most computers now have full-color displays, palettes are
rarely needed. RGB colors specified in an application are mapped to the
nearest display color with no need for a palette.
A wxPalette can be created by passing a size and three arrays (unsigned char*) for each of the red, green, and blue components. You can query the number of colors with GetColoursCount. To find the red, green, and blue values for a given index, use GetRGB, and you can find an index value for given red, green, and blue values with GetPixel.
Set the palette into a client, window, or memory device context with wxDC::SetPalette. For example, you can set the palette obtained from a low-depth wxBitmap you are about to draw, so the system knows how to map the index values to device colors. When using drawing functions that use wxColour
with a device context that has a palette set, the RGB color will be
mapped automatically to the palette index by the system, so choose a
palette that closely matches the colors you will be using.
Another use for wxPalette is to query a wxImage or wxBitmap for the colors in a low-color image that was loaded from a file, such as a GIF. If there is an associated wxPalette
object, it will give you a quick way to identify the unique colors in
the original file, even though the image will have been converted to an
RGB representation. Similarly, you can create and associate a palette
with a wxImage that is to be saved in a reduced-color format. For example, the following fragment loads a PNG file and saves it as an 8-bit Windows bitmap file:
// Load the PNG
wxImage image(wxT("image.png"), wxBITMAP_TYPE_PNG);
// Make a palette
unsigned char* red = new unsigned char[256];
unsigned char* green = new unsigned char[256];
unsigned char* blue = new unsigned char[256];
for (size_t i = 0; i < 256; i ++)
{
red[i] = green[i] = blue[i] = i;
}
wxPalette palette(256, red, green, blue);
// Set the palette and the BMP depth
image.SetPalette(palette);
image.SetOption(wxIMAGE_OPTION_BMP_FORMAT, wxBMP_8BPP_PALETTE);
// Save the file
image.SaveFile(wxT("image.bmp"), wxBITMAP_TYPE_BMP);
More realistic code would "quantize" the image to reduce the number
of colors; see "Color Reduction" in Chapter 10, "Programming with
Images," for use of the wxQuantize class to do this.
wxWidgets defines a null palette object, wxNullPalette.