Simple GDI plus drawing example

posted on 4/4/2015 5:47 AM by Eric Butler

One of the fundamentals of Windows desktop programming is drawing, and depending on your application, you may need to do a lot of it. In this example, I'll show you how to set up a simple form and draw on it using C++ and GD+.

What is GDI+?

GDI+ is a drawing library built on top of GDI, which allows you to create graphical applications with relative ease! GDI+ supports colors with alpha channels, so you can draw shapes and lines with transparency. GDI+ has a ton of other great feature too, like built in support for drawing bitmaps and saving bitmaps.

When you are ready to start drawing, you create a Graphics object using an DC, then begin painting with that Graphics object.

//create a graphics object from the main window hdc
Graphics g(hdc);

//pens and brushes
Pen pen(Color(255, 0, 255, 128));

//draw a circle
graphics.DrawEllipse(&pen, 200, 50, 100, 100);

I created a sample C++ application that demonstrates some very basic drawing functions.

This example shows how to create some simple gradients, lines, ellipsis and rectangles. There is even an animated bouncing ball!

First, we have to include GDI+ in our application:

#include  <gdiplus.h>

using namespace Gdiplus;

/* We need to include the Gdiplus lib */
#pragma comment (lib, "Gdiplus.lib")

Next, we need to start up the GDI+ library:

//gdi+ startup input
GdiplusStartupInput gdiplusStartupInput;

//gdi+ token
ULONG_PTR gdiplusToken;

//initialize GDI+
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

//initialize your window, run your message loop, etc...
//when finished and your application is ending, shut down gdi+

//shut down gdi+

Our drawing takes place in the WndProc WM_PAINT message. Here we create our PaintStruct and HDC to pass to our OnPaint function:

case WM_PAINT:
		HDC hdc;
		//get the hdc from our hwnd
		hdc = BeginPaint(hwnd, &ps);

		//call our drawing method
		OnPaint(hwnd, hdc);

		//end painting
		EndPaint(hwnd, &ps);

		return 0;

Is GDI+ right for me?

GDI+ has some disadvangages. Number one drawback? Its slow. Ok, its not too slow, but there are performace issues when rendering large images. In our animation example, I use a backbuffer strategy where I create a blank image to draw on, then when drawing is done, I draw that image onto the main graphics object created from the DC of the window. This eliminates nasty flicker, but slows down considerably as the window size increases.

But it does have advantages. If you are looking to draw with alpha channels, or you want access to higher level drawing functions (which make drawing a snap), then GDI may be for you. You don't always need to backbuffer, so you may not notice too much of a performance hit.


As a thank-you, please consider sending a small donation. You can contribute as much as you'd like.


Log in to leave a comment

Log In