Drawing and Printing in C++ with wxWidgets
- Understanding Device Contexts
- Drawing Tools
- Device Context Drawing Functions
- Using the Printing Framework
- 3D Graphics with wxGLCanvas
- Summary
This chapter introduces the idea of the device context, generalizing the concept of a drawing surface such as a window or a printed page. We will discuss the available device context classes and the set of "drawing tools" that wxWidgets provides for handling fonts, color, line drawing, and filling. Next we describe a device context's drawing functions and how to use the wxWidgets printing framework. We end the chapter by briefly discussing wxGLCanvas, which provides a way for you to draw 3D graphics on your windows using OpenGL.
Understanding Device Contexts
All drawing in wxWidgets is done on a device context, using an instance of a class derived from wxDC. There is no such thing as drawing directly to a window; instead, you create a device context for the window and then draw on the device context. There are also device context classes that work with bitmaps and printers, or you can design your own. A happy consequence of this abstraction is that you can define drawing code that will work on a number of different device contexts: just parameterize it with wxDC, and if necessary, take into account the device's resolution by scaling appropriately. Let's describe the major properties of a device context.
A device context has a coordinate system with its origin at the top-left of the surface. This position can be changed with SetDeviceOrigin so that graphics subsequently drawn on the device context are shifted—this is used when painting with wxScrolledWindow. You can also use SetAxisOrientation if you prefer, say, the y-axis to go from bottom to top.
There is a distinction between logical units and device units. Device units are the units native to the particular device—for a screen, a device unit is a pixel. For a printer, the device unit is defined by the resolution of the printer, which can be queried using GetSize (for a page size in device units) or GetSizeMM (for a page size in millimeters).
The mapping mode of the device context defines the unit of measurement used to convert logical units to device units. Note that some device contexts, in particular wxPostScriptDC, do not support mapping modes other than wxMM_TEXT. Table 5-1 lists the available mapping modes.
Table 5-1. Mapping Modes
wxMM_TWIPS |
Each logical unit is 1/20 of a point, or 1/1440 of an inch. |
wxMM_POINTS |
Each logical unit is a point, or 1/72 of an inch. |
wxMM_METRIC |
Each logical unit is 1 millimeter. |
wxMM_LOMETRIC |
Each logical unit is 1/10 of a millimeter. |
wxMM_TEXT |
Each logical unit is 1 pixel. This is the default mode. |
You can impose a further scale on your logical units by calling SetUser Scale, which multiplies with the scale implied by the mapping mode. For example, in wxMM_TEXT mode, a user scale value of (1.0, 1.0) makes logical and device units identical. By default, the mapping mode is wxMM_TEXT, and the scale is (1.0, 1.0).
A device context has a clipping region, which can be set with SetClipping Region and cleared with DestroyClippingRegion. Graphics will not be shown outside the clipping region. One use of this is to draw a string so that it appears only inside a particular rectangle, even though the string might extend beyond the rectangle boundary. You can set the clipping region to be the same size and location as the rectangle, draw the text, and then destroy the clipping region, and the text will be truncated to fit inside the rectangle.
Just as with real artistry, in order to draw, you must first select some tools. Any operation that involves drawing an outline uses the currently selected pen, and filled areas use the current brush. The current font, together with the foreground and background text color, determines how text will appear. We will discuss these tools in detail later, but first we'll look at the types of device context that are available to us.
Available Device Contexts
These are the device context classes you can use:
- wxClientDC. For drawing on the client area of a window.
- wxBufferedDC. A replacement for wxClientDC for double-buffered painting.
- wxWindowDC. For drawing on the client and non-client (decorated) area of a window. This is rarely used and not fully implemented on all platforms.
- wxPaintDC. For drawing on the client area of a window during a paint event handler.
- wxBufferedPaintDC. A replacement for wxPaintDC for double-buffered painting.
- wxScreenDC. For drawing on or copying from the screen.
- wxMemoryDC. For drawing into or copying from a bitmap.
- wxMetafileDC. For creating a metafile (Windows and Mac OS X).
- wxPrinterDC. For drawing to a printer.
- wxPostScriptDC. For drawing to a PostScript file or printer.
The following sections describe how to create and work with these device contexts. Working with printer device contexts is discussed in more detail later in the chapter in "Using the Printing Framework."
Drawing on Windows with wxClientDC
Use wxClientDC objects to draw on the client area of windows outside of paint events. For example, to implement a doodling application, you might create a wxClientDC object within your mouse event handler. It can also be used within background erase events.
Here's a code fragment that demonstrates how to paint on a window using the mouse:
BEGIN_EVENT_TABLE(MyWindow, wxWindow) EVT_MOTION(MyWindow::OnMotion) END_EVENT_TABLE() void MyWindow::OnMotion(wxMouseEvent& event) { if (event.Dragging()) { wxClientDC dc(this); wxPen pen(*wxRED, 1); // red pen of width 1 dc.SetPen(pen); dc.DrawPoint(event.GetPosition()); dc.SetPen(wxNullPen); } }
For more realistic doodling code, see Chapter 19, "Working with Documents and Views." The "Doodle" example uses line segments instead of points and implements undo/redo. It also stores the line segments, so that when the window is repainted, the graphic is redrawn; using the previous code, the graphic will only linger on the window until the next paint event is received. You may also want to use CaptureMouse and ReleaseMouse to direct all mouse events to your window while the mouse button is down.
An alternative to using wxClientDC directly is to use wxBufferedDC, which stores your drawing in a memory device context and transfers it to the window in one step when the device context is about to be deleted. This can result in smoother updates—for example, if you don't want the user to see a complex graphic being updated bit by bit. Use the class exactly as you would use wxClientDC. For efficiency, you can pass a stored bitmap to the constructor to avoid the object re-creating a bitmap each time.
Erasing Window Backgrounds
A window receives two kinds of paint event: wxPaintEvent for drawing the main graphic, and wxEraseEvent for painting the background. If you just handle wxPaintEvent, the default wxEraseEvent handler will clear the background to the color previously specified by wxWindow::SetBackgroundColour, or a suitable default.
This may seem rather convoluted, but this separation of background and foreground painting enables maximum control on platforms that follow this model, such as Windows. For example, suppose you want to draw a textured background on a window. If you tile your texture bitmap in OnPaint, you will see a brief flicker as the background is cleared prior to painting the texture. To avoid this, handle wxEraseEvent and do nothing in the handler. Alternatively, you can do the background tiling in the erase handler, and paint the foreground in the paint handler (however, this defeats buffered drawing as described in the next section).
On some platforms, intercepting wxEraseEvent still isn't enough to suppress default background clearing. The safest thing to do if you want to have a background other than a plain color is to call wxWindow::SetBackgroundStyle passing wxBG_STYLE_CUSTOM. This tells wxWidgets to leave all background painting to the application.
If you do decide to implement an erase handler, call wxEraseEvent::GetDC and use the returned device context if it exists. If it's NULL, you can use a wxClientDC instead. This allows for wxWidgets implementations that don't pass a device context to the erase handler, which can be an unnecessary expense if it's not used. This is demonstrated in the following code for drawing a bitmap as a background texture:
BEGIN_EVENT_TABLE(MyWindow, wxWindow) EVT_ERASE_BACKGROUND(MyWindow::OnErase) END_EVENT_TABLE() void MyWindow::OnErase(wxEraseEvent& event) { wxClientDC* clientDC = NULL; if (!event.GetDC()) clientDC = new wxClientDC(this); wxDC* dc = clientDC ? clientDC : event.GetDC() ; wxSize sz = GetClientSize(); wxEffects effects; effects.TileBitmap(wxRect(0, 0, sz.x, sz.y), *dc, m_bitmap); if (clientDC) delete clientDC; }
As with paint events, the device context will be clipped to the area that needs to be repaired, if using the object returned from wxEraseEvent::GetDC.
Drawing on Windows with wxPaintDC
If you define a paint event handler, you must always create a wxPaintDC object, even if you don't use it. Creating this object will tell wxWidgets that the invalid regions in the window have been repainted so that the windowing system won't keep sending paint events ad infinitum. In a paint event, you can call wxWindow::GetUpdateRegion to get the region that is invalid, or wxWindow::IsExposed to determine if the given point or rectangle is in the update region. If possible, just repaint this region. The device context will automatically be clipped to this region anyway during the paint event, but you can speed up redraws by only drawing what is necessary.
Paint events are generated when user interaction causes regions to need repainting, but they can also be generated as a result of wxWindow::Refresh or wxWindow::RefreshRect calls. If you know exactly which area of the window needs to be repainted, you can invalidate that region and cause as little flicker as possible. One problem with refreshing the window this way is that you can't guarantee exactly when the window will be updated. If you really need to have the paint handler called immediately—for example, if you're doing time- consuming calculations—you can call wxWindow::Update after calling Refresh or RefreshRect.
The following code draws a red rectangle with a black outline in the center of a window, if the rectangle was in the update region:
BEGIN_EVENT_TABLE(MyWindow, wxWindow) EVT_PAINT(MyWindow::OnPaint) END_EVENT_TABLE() void MyWindow::OnPaint(wxPaintEvent& event) { wxPaintDC dc(this); dc.SetPen(*wxBLACK_PEN); dc.SetBrush(*wxRED_BRUSH); // Get window dimensions wxSize sz = GetClientSize(); // Our rectangle dimensions wxCoord w = 100, h = 50; // Center the rectangle on the window, but never // draw at a negative position. int x = wxMax(0, (sz.x—w)/2); int y = wxMax(0, (sz.y—h)/2); wxRect rectToDraw(x, y, w, h); // For efficiency, do not draw if not exposed if (IsExposed(rectToDraw)) DrawRectangle(rectToDraw); }
Note that by default, when a window is resized, only the newly exposed areas are included in the update region. Use the wxFULL_REPAINT_ON_RESIZE window style to have the entire window included in the update region when the window is resized. In our example, we need this style because resizing the window changes the position of the graphic, and we need to make sure that no odd bits of the rectangle are left behind.
wxBufferedPaintDC is a buffered version of wxPaintDC. Simply replace wxPaintDC with wxBufferedPaintDC in your paint event handler, and the graphics will be drawn to a bitmap before being drawn all at once on the window, reducing flicker.
As we mentioned in the previous topic, another thing you can do to make drawing smoother (particularly when resizing) is to paint the background in your paint handler, and not in an erase background handler. All the painting will then be done in your buffered paint handler, so you don't see the background being erased before the paint handler is called. Add an empty erase background handler, and call SetBackgroundStyle with wxBG_STYLE_CUSTOM to hint to some systems not to clear the background automatically. In a scrolling window, where the device origin is moved to shift the graphic for the current scroll position, you will need to calculate the position of the window client area for the current origin. The following code snippet illustrates how to achieve smooth painting and scrolling for a class derived from wxScrolledWindow:
#include "wx/dcbuffer.h" BEGIN_EVENT_TABLE(MyCustomCtrl, wxScrolledWindow) EVT_PAINT(MyCustomCtrl::OnPaint) EVT_ERASE_BACKGROUND(MyCustomCtrl::OnEraseBackground) END_EVENT_TABLE() /// Painting void MyCustomCtrl::OnPaint(wxPaintEvent& event) { wxBufferedPaintDC dc(this); // Shifts the device origin so we don't have to worry // about the current scroll position ourselves PrepareDC(dc); // Paint the background PaintBackground(dc); // Paint the graphic ... } /// Paint the background void MyCustomCtrl::PaintBackground(wxDC& dc) { wxColour backgroundColour = GetBackgroundColour(); if (!backgroundColour.Ok()) backgroundColour = wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE); dc.SetBrush(wxBrush(backgroundColour)); dc.SetPen(wxPen(backgroundColour, 1)); wxRect windowRect(wxPoint(0, 0), GetClientSize()); // We need to shift the client rectangle to take into account // scrolling, converting device to logical coordinates CalcUnscrolledPosition(windowRect.x, windowRect.y, & windowRect.x, & windowRect.y); dc.DrawRectangle(windowRect); } // Empty implementation, to prevent flicker void MyCustomCtrl::OnEraseBackground(wxEraseEvent& event) { }
To increase efficiency when using wxBufferedPaintDC, you can maintain a bitmap large enough to cope with all window sizes (for example, the screen size) and pass it to the wxBufferedPaintDC constructor as its second argument. Then the device context doesn't have to keep creating and destroying its bitmap for every paint event.
The area that wxBufferedPaintDC copies from its buffer is normally the size of the window client area (the part that the user can see). The actual paint context that is internally created by the class is not transformed by the window's PrepareDC to reflect the current scroll position. However, you can specify that both the paint context and your buffered paint context use the same transformations by passing wxBUFFER_VIRTUAL_AREA to the wxBufferedPaintDC constructor, rather than the default wxBUFFER_CLIENT_AREA. Your window's PrepareDC function will be called on the actual paint context so the transformations on both device contexts match. In this case, you will need to supply a bitmap that is the same size as the virtual area in your scrolled window. This is inefficient and should normally be avoided. Note that at the time of writing, using buffering with wxBUFFER_CLIENT_AREA does not work with scaling (SetUserScale).
For a full example of using wxBufferedPaintDC, you might like to look at the wxThumbnailCtrl control in examples/chap12/thumbnail on the CD-ROM.
Drawing on Bitmaps with wxMemoryDC
A memory device context has a bitmap associated with it, so that drawing into the device context draws on the bitmap. First create a wxMemoryDC object with the default constructor, and then use SelectObject to associate a bitmap with the device context. When you have finished with the device context, you should call SelectObject with wxNullBitmap to remove the association.
The following example creates a bitmap and draws a red rectangle outline on it:
wxBitmap CreateRedOutlineBitmap() { wxMemoryDC memDC; wxBitmap bitmap(200, 200); memDC.SelectObject(bitmap); memDC.SetBackground(*wxWHITE_BRUSH); memDC.Clear(); memDC.SetPen(*wxRED_PEN); memDC.SetBrush(*wxTRANSPARENT_BRUSH); memDC.DrawRectangle(wxRect(10, 10, 100, 100)); memDC.SelectObject(wxNullBitmap); return bitmap; }
You can also copy areas from a memory device context to another device context with the Blit function, described later in the chapter.
Creating Metafiles with wxMetafileDC
wxMetafileDC is available on Windows and Mac OS X, where it models a drawing surface for a Windows metafile or a Mac PICT, respectively. It allows you to draw into a wxMetafile object, which consists of a list of drawing instructions that can be interpreted by an application or rendered into a device context with wxMetafile::Play.
Accessing the Screen with wxScreenDC
Use wxScreenDC for drawing on areas of the whole screen. This is useful when giving feedback for dragging operations, such as the sash on a splitter window. For efficiency, you can limit the screen area to be drawn on to a specific region (often the dimensions of the window in question). As well as drawing with this class, you can copy areas to other device contexts and use it for capturing screenshots. Because it is not possible to control where other applications are drawing, use of wxScreenDC to draw on the screen usually works best when restricted to windows in the current application.
Here's example code that snaps the current screen and returns it in a bitmap:
wxBitmap GetScreenShot() { wxSize screenSize = wxGetDisplaySize(); wxBitmap bitmap(screenSize.x, screenSize.y); wxScreenDC dc; wxMemoryDC memDC; memDC.SelectObject(bitmap); memDC.Blit(0, 0, screenSize.x, screenSize.y, & dc, 0, 0); memDC.SelectObject(wxNullBitmap); return bitmap; }
Printing with wxPrinterDC and wxPostScriptDC
wxPrinterDC represents the printing surface. On Windows and Mac, it maps to the respective printing system for the application. On other Unix-based systems where there is no standard printing model, a wxPostScriptDC is used instead, unless GNOME printing support is available (see the later section, "Printing Under Unix with GTK+").
There are several ways to construct a wxPrinterDC object. You can pass it a wxPrintData after setting paper type, landscape or portrait, number of copies, and so on. An easier way is to show a wxPrintDialog and then call wxPrintDialog::GetPrintDC to retrieve an appropriate wxPrinterDC for the settings chosen by the user. At a higher level, you can derive a class from wxPrintout to specify behavior for printing and print previewing, passing it to an instance of wxPrinter (see the later section on printing).
If your printout is mainly text, consider using the wxHtmlEasyPrinting class to bypass the need to deal with wxPrinterDC or wxPrintout altogether: just write an HTML file (using wxWidgets' subset of HTML syntax) and create a wxHtmlEasyPrinting object to print or preview it. This could save you days or even weeks of programming to format your text, tables, and images. See Chapter 12, "Advanced Window Classes," for more on this.
wxPostScriptDC is a device context specifically for creating PostScript files for sending to a printer. Although mainly for Unix-based systems, it can be used on other systems too, where PostScript files need to be generated and you can't guarantee the presence of a PostScript printer driver.
You can create a wxPostScriptDC either by passing a wxPrintData object, or by passing a file name, a boolean to specify whether a print dialog should be shown, and a parent window for the dialog. For example:
#include "wx/dcps.h" wxPostScriptDC dc(wxT("output.ps"), true, wxGetApp().GetTopWindow()); if (dc.Ok()) { // Tell it where to find the AFM files dc.GetPrintData().SetFontMetricPath(wxGetApp().GetFontPath()); // Set the resolution in points per inch (the default is 720) dc.SetResolution(1440); // Draw on the device context ... }
One of the quirks of wxPostScriptDC is that it can't directly return text size information from GetTextExtent. You will need to provide AFM (Adobe Font Metric) files with your application and use wxPrintData::SetFontMetricPath to specify where wxWidgets will find them, as in this example. You can get a selection of GhostScript AFM files from ftp://biolpc22.york.ac.uk/pub/support/gs_afm.tar.gz.