Home > Articles > Programming > User Interface (UI)

This chapter is from the book

Device Context Drawing Functions

In this section, we'll take a closer look at how we draw on device contexts. The major functions are summarized in Table 5-5. We cover most of them in the following sections, and you can also find more details in the reference manual.

Table 5-5. Device Context Functions


Copies from one device context to another. You can specify how much of the original to draw, where drawing should start, the logical function to use, and whether to use a mask if the source is a memory device context.


Fills the device context with the current background brush.


Sets and destroys the clipping region, which restricts drawing to a specified area. The clipping region can be specified as a rectangle or a wxRegion. Use GetClippingBox to get the rectangle surrounding the current clipping region.


Draws an arc or elliptic arc using the current pen and brush.


Draws a wxBitmap or wxIcon at the specified location.


The bitmap may have a mask to specify transparency.


Draws a circle using the current pen and brush.


Draws an ellipse using the current pen and brush.


Draws a line or number of lines using the current pen. The last point of the line is not drawn.


Draws a point using the current pen.


DrawPolygon draws a filled polygon using an array of points or list of pointers to points, adding an optional offset coordinate. wxWidgets automatically closes the first and last points. DrawPolyPolygon draws one or more polygons at once, which can be a more efficient operation on some platforms.


Draws a rectangle or rounded rectangle using the current pen and brush.


Draws a text string, or rotated text string, at the specified point using the current text font and the current text foreground and background colors.


Draws a spline between all given control points, using the current pen.


Flood fills the device context starting from the given point, using the current brush color.


Returns true if the device context is OK to use.


Sets and gets the background brush used in Clear and in functions that use a complex logical function. The default is wxTRANSPARENT_BRUSH.


Sets and gets the background mode for drawing text: wxSOLID or wxTRANSPARENT. Normally, you will want to set the mode to wxTRANSPARENT (the default) so the existing background will be kept when drawing text.


Sets and gets the brush to be used to fill shapes in subsequent drawing operations. The initial value of the brush is undefined.


Sets and gets the pen to be used to draw the outline of shapes in subsequent drawing operations. The initial value of the pen is undefined.


Sets and gets the font to be used in DrawText, DrawRotatedText, and GetTextExtent calls. The initial value of the font is undefined.


Sets and gets wxPalette object mapping index values to RGB colors.


Sets and gets the color to be used for text foreground and background. The defaults are black and white, respectively.


The logical function determines how a source pixel from a pen or brush color, or source device context if using Blit, combines with a destination pixel in the current device context. The default is wxCOPY, which simply draws with the current color.


Returns the color at the given point. This is not implemented for wxPostScriptDC and wxMetafileDC.


Returns metrics for a given text string.


Returns the dimensions of the device in device units or millimeters.


Starts and ends a document. This is only applicable to printer device contexts. When StartDoc is called, a message will be shown as the document is printed, and EndDoc will hide the message box.


Starts and ends a page. This is only applicable to printer device contexts.


Converts device coordinates to logical coordinates, either absolute (for positions) or relative (for widths and heights).


Converts logical coordinates to device coordinates, either absolute (for positions) or relative (for widths and heights).


As described earlier, this determines (along with SetUserScale) how logical units are converted to device units.


Sets the x- and y-axis orientation: the direction from lowest to highest values on the axis. The default orientation is to have the x-axis from left to right (true) and the y-axis from top to bottom (false).


Sets and gets the device origin. You can use this to place a graphic in a particular place on a page, for example.


Sets and gets the scale to be applied when converting from logical units to device units.

Drawing Text

The way text is drawn on a device context with DrawText is determined by the current font, the background mode (transparent or solid drawing), and the text foreground and background colors. If the background mode is wxSOLID, the area behind the text will be drawn in the current background color, and if wxTRANSPARENT, the text will be drawn without disturbing the background.

Pass a string and either two integers or a wxPoint to DrawText. The text will be drawn with the given location at the very top-left of the string. Here's a simple example of drawing a text string:

// Draw a text string on a window at the given point
void DrawTextString(wxDC& dc, const wxString& text,
                    const wxPoint& pt)
    wxFont font(12, wxFONTFAMILY_SWISS, wxNORMAL, wxBOLD);
    dc.DrawText(text, pt);

You can also use the device context function DrawRotatedText to draw text at an angle by specifying the angle in degrees as the last parameter. The following code draws text at 45-degree increments, and the result is illustrated in Figure 5-2.

wxFont font(20, wxFONTFAMILY_SWISS, wxNORMAL, wxNORMAL);


for (int angle = 0; angle < 360; angle += 45)
    dc.DrawRotatedText(wxT("Rotated text..."), 300, 300, angle);

Figure 5-2 Drawing rotated text

On Windows, only TrueType fonts can be drawn rotated. Be aware that the stock object wxNORMAL_FONT is not TrueType.

Often, you'll need to find out how much space text will take on a device context, which you can do by passing wxCoord (integer) pointers to the function GetTextExtent. Its prototype is

void GetTextExtent(const wxString& string,
    wxCoord* width, wxCoord* height,
    wxCoord* descent = NULL, wxCoord* externalLeading = NULL,
    wxFont* font = NULL);

The default arguments mean that you can call it just to find the overall width and height the string occupies, or you can pass extra arguments to get further text dimensions. If you imagine the bottoms of the characters sitting on a baseline, the descent is how far below the baseline the characters extend. The letter "g," for example, extends below the baseline. External leading is the space between the descent of one line and the top of the line below. Finally, you can provide a font to be used in place of the current device context font.

Here's code that uses GetTextExtent to center a string on a window:

void CenterText(const wxString& text, wxDC& dc, wxWindow* win)
    // Set font, background mode for drawing text,
    // and text color

    // Get window and text dimensions
    wxSize sz = win->GetClientSize();
    wxCoord w, h;
    dc.GetTextExtent(text, & w, & h);

    // Center the text 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);

    dc.DrawText(msg, x, y);

You can also use GetPartialTextExtents to retrieve the width of each character, passing a wxString and a wxArrayInt reference to receive the character width values. If you need accurate information about individual character widths, this can be quicker on some platforms than calling GetTextExtent for each character.

Drawing Lines and Shapes

The simpler drawing primitives include points, lines, rectangles, circles, and ellipses. The current pen determines the line or outline color, and the brush determines the fill color. For example:

void DrawSimpleShapes(wxDC& dc)
    // Set line color to black, fill color to green
    dc.SetPen(wxPen(*wxBLACK, 2, wxSOLID));
    dc.SetBrush(wxBrush(*wxGREEN, wxSOLID));

    // Draw a point
    dc.DrawPoint(5, 5);

    // Draw a line
    dc.DrawLine(10, 10, 100, 100);

    // Draw a rectangle at (50, 50) with size (150, 100)
    // and hatched brush
    dc.SetBrush(wxBrush(*wxBLACK, wxCROSS_HATCH));
    dc.DrawRectangle(50, 50, 150, 100);

    // Set a red brush

    // Draw a rounded rectangle at (150, 20) with size (100, 50)
    // and corner radius 10
    dc.DrawRoundedRectangle(150, 20, 100, 50, 10);

    // Draw another rounded rectangle with no border
    dc.DrawRoundedRectangle(250, 80, 100, 50, 10);

    // Set a black pen and black brush
    dc.SetPen(wxPen(*wxBLACK, 2, wxSOLID));

    // Draw a circle at (100, 150) with radius 60
    dc.DrawCircle(100, 150, 60);

    // Set a white brush

    // Draw an ellipse that fills the given rectangle
    dc.DrawEllipse(wxRect(120, 120, 150, 50));

This produces the graphic in Figure 5-3.


Figure 5-3 Drawing simple shapes

Note that by convention, the last point of a line is not drawn.

To draw a circular arc, use DrawArc, taking a starting point, end point, and center point. The arc is drawn counterclockwise from the starting point to the end. For example:

// Draw a cup-shaped arc
int x = 10, y = 200, radius = 20;
dc.DrawArc(x–radius, y, x + radius, y, x, y);

This produces the arc shown in Figure 5-4.


Figure 5-4 A circular arc

For an elliptic arc, DrawEllipticArc takes the position and size of a rectangle that contains the arc, plus the start and end of the arc in degrees specified from the three o'clock position from the center of the rectangle. If the start and end points are the same, a complete ellipse will be drawn. The following code draws the arc shown in Figure 5-5.

// Draws an elliptical arc within a rectangle at (10, 100),
// size 200x40. Arc extends from 270 to 420 degrees.
dc.DrawEllipticArc(10, 100, 200, 40, 270, 420);

Figure 5-5 An elliptical arc

If you need to draw a lot of lines quickly, DrawLines can be more efficient than using DrawLine multiple times. The following example draws lines between ten points, at an offset of (100, 100).

wxPoint points[10];
for (size_t i = 0; i < 10; i++)
  pt.x = i*10; pt.y = i*20;

int offsetX = 100;
int offsetY = 100;

dc.DrawLines(10, points, offsetX, offsetY);

DrawLines does not fill the area surrounded by the lines. You can draw a filled shape with an arbitrary number of sides using DrawPolygon, and several of them with DrawPolyPolygon. DrawPolygon takes a point count, an array of points, optional offsets to add to the points, and an optional fill style: wxODDEVEN_RULE, the default, or wxWINDING_RULE. DrawPolygonPolygon additionally takes an array of integers that specifies the number of points to be used for each polygon.

The following code demonstrates how to draw polygons and poly- polygons, with the result shown in Figure 5-6.

void DrawPolygons(wxDC& dc)
    wxBrush brushHatch(*wxRED, wxFDIAGONAL_HATCH);

    wxPoint star[5];
    star[0] = wxPoint(100, 60);
    star[1] = wxPoint(60, 150);
    star[2] = wxPoint(160, 100);
    star[3] = wxPoint(40, 100);
    star[4] = wxPoint(140, 150);

    dc.DrawPolygon(WXSIZEOF(star), star, 0, 30);
    dc.DrawPolygon(WXSIZEOF(star), star, 160, 30, wxWINDING_RULE);

    wxPoint star2[10];
    star2[0] = wxPoint(0, 100);
    star2[1] = wxPoint(-59, -81);
    star2[2] = wxPoint(95, 31);
    star2[3] = wxPoint(-95, 31);
    star2[4] = wxPoint(59, -81);
    star2[5] = wxPoint(0, 80);
    star2[6] = wxPoint(-47, -64);
    star2[7] = wxPoint(76, 24);
    star2[8] = wxPoint(-76, 24);
    star2[9] = wxPoint(47, -64);
    int count[2] = {5, 5};

    dc.DrawPolyPolygon(WXSIZEOF(count), count, star2, 450, 150);

Figure 5-6 Drawing polygons

Drawing Splines

DrawSpline lets you draw a curve known as a "spline" between multiple points. There is a version for three points, and a version for an arbitrary number of points, both illustrated in this example code:

// Draw 3-point sline
dc.DrawSpline(10, 100, 200, 200, 50, 230);

// Draw 5-point spline
wxPoint star[5];
star[0] = wxPoint(100, 60);
star[1] = wxPoint(60, 150);
star[2] = wxPoint(160, 100);
star[3] = wxPoint(40, 100);
star[4] = wxPoint(140, 150);
dc.DrawSpline(WXSIZEOF(star), star);

This produces the two splines illustrated in Figure 5-7.


Figure 5-7 Drawing splines

Drawing Bitmaps

There are two main ways of drawing bitmaps on a device context: DrawBitmap and Blit. DrawBitmap is a simplified form of Blit, and it takes a bitmap, a position, and a boolean flag specifying transparent drawing. The transparency can be either a simple mask or an alpha channel (which offers translucency), depending on how the bitmap was loaded or created. The following code loads an image with an alpha channel and draws it over lines of text.

wxString msg = wxT("Some text will appear mixed in the image's shadow...");
int y = 75;
for (size_t i = 0; i < 10; i++)
    y += dc.GetCharHeight() + 5;
    dc.DrawText(msg, 200, y);

wxBitmap bmp(wxT("toucan.png"), wxBITMAP_TYPE_PNG);
dc.DrawBitmap(bmp, 250, 100, true);

This produces the drawing in Figure 5-8, where the shadows in the bitmap appear to partially obscure the text underneath.


Figure 5-8 Drawing with transparency

The Blit function is more flexible and enables you to copy a specific portion of a source device context onto a destination device context. This is its prototype:

bool Blit(wxCoord destX, wxCoord destY,
          wxCoord width, wxCoord height, wxDC* dcSource,
          wxCoord srcX, wxCoord srcY,
          int logicalFunc = wxCOPY,
          bool useMask = false,
          wxCoord srcMaskX = -1, wxCoord srcMaskY = -1);

This code copies an area from a source device context dcSource to the destination (the object that the function is operating on). An area of specified width and height is drawn starting at the position (destX, destY) on the destination surface, taken from the position (srcX, srcY) on the source. The logical function logicalFunc is usually wxCOPY, which means the bits are transferred from source to destination with no transformation. Not all platforms support a logical function other than wxCOPY. For more information, please see "Logical Functions" later in this chapter.

The last three parameters are used only when the source device context is a wxMemoryDC with a transparent bitmap selected into it. useMask specifies whether transparent drawing is used, and srcMaskX and srcMaskY enable the bitmap's mask to start from a different position than the main bitmap start position.

The following example loads a small pattern into a bitmap and uses Blit to fill a larger destination bitmap, with transparency if available.

wxMemoryDC dcDest;
wxMemoryDC dcSource;

int destWidth = 200, destHeight = 200;

// Create the destination bitmap
wxBitmap bitmapDest(destWidth, destHeight);

// Load the pattern bitmap
wxBitmap bitmapSource(wxT("pattern.png"), wxBITMAP_TYPE_PNG);

int sourceWidth = bitmapSource.GetWidth();
int sourceHeight = bitmapSource.GetHeight();

// Clear the destination background to white


// Tile the smaller bitmap onto the larger bitmap
for (int i = 0; i < destWidth; i += sourceWidth)
    for (int j = 0; j < destHeight; j += sourceHeight)
        dcDest.Blit(i, j, sourceWidth, sourceHeight,
                    & dcSource, 0, 0, wxCOPY, true);

// Tidy up

You can also draw icons directly, with DrawIcon. This operation always takes transparency into account. For example:

#include "file.xpm"

wxIcon icon(file_xpm);
dc.DrawIcon(icon, 20, 30); 

Filling Arbitrary Areas

FloodFill can be used to fill an arbitrary area of a device context up to a color boundary. Pass a starting point, a color for finding the flood area boundary, and a style to indicate how the color parameter should be used. The device context will be filled with the current brush color.

The following example draws a green rectangle with a red border and fills it with black, followed by blue.

// Draw a green rectangle outlines in red

dc.DrawRectangle(10, 10, 100, 100);

// Now fill the green area with black (while green is found)
dc.FloodFill(50, 50, *wxGREEN, wxFLOOD_SURFACE);

// Then fill with blue (until red is encountered)
dc.FloodFill(50, 50, *wxRED, wxFLOOD_BORDER);

The function may fail if it cannot find the color specified, or the point is outside the clipping region. FloodFill won't work with printer device contexts, or with wxMetafileDC.

Logical Functions

The current logical function determines how a source pixel (from a pen or brush color, or source device context if using Blit) combines with a destination pixel in the current device context. The default is wxCOPY, which simply draws with the current color. The others combine the current color and the background using a logical operation. wxINVERT is commonly used for drawing rubber bands or moving outlines because with this operation drawing a shape the second time erases the shape.

The following example draws a dotted line using wxINVERT and then erases it before restoring the normal logical function.

wxPen pen(*wxBLACK, 1, wxDOT);

// Invert pixels
dc.DrawLine(10, 10, 100, 100);

// Invert again, rubbing it out
dc.DrawLine(10, 10, 100, 100);

// Restore to normal drawing

Another use for logical functions is to combine images to create new images. For example, here's one method for creating transparent jigsaw puzzle pieces out of an image. First, draw a black outline of each shape on a white bitmap, using a grid of standard (but randomized) puzzle edges. Then, for each piece, flood-fill the outline to create a black puzzle shape on a white background. Blit the corresponding area of the puzzle image onto this template bitmap with the wxAND_REVERSE function to mask out the unwanted parts of the puzzle, leaving the "stamped out" puzzle piece on a black background. This can be made into a transparent wxBitmap by converting to a wxImage, setting black as the image mask color, and converting back to a transparent wxBitmap, which can be drawn appropriately. (Note that this technique depends on there being no black in the puzzle image, or else holes will appear in the puzzle pieces.)

Table 5-6 shows the logical function values and their meanings.

Table 5-6. Logical Functions

Logical Function

Meaning ( src = source, dst = destination)


src AND dst


(NOT src) AND dst


src AND (NOT dst)






(NOT src) XOR dst


NOT dst


(NOT src) OR (NOT dst)


(NOT src) AND (NOT dst)




src OR dst


(NOT src) OR dst


src OR (NOT dst)




NOT src


src XOR dst

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020