Drawing Text with GDI+

Toast picture Toast · Sep 4, 2011 · Viewed 28k times · Source

I have searched for some days now to find a possibility to display text on my GDI+ application.

I tried using the DrawString() function of GDI+ but the reference on MSDN does not work as it does not match with the parameter list. I am using Visual C++ 2010 Express.

I changed the MSDN example to make it compile, like this:

LinearGradientBrush* myBrush = new LinearGradientBrush(Rect(0,0,width,height),Color::Red, Color::Yellow, LinearGradientMode::LinearGradientModeHorizontal);
Font* myFont = new Font(hdc);
RectF rect = RectF(10,10,100,100);
graphics.DrawString(TEXT("Look at this text!"),100, myFont,rect,&StringFormat(0,0), myBrush);

I also tried two other functions:

TextOut(hdc,10,10,TEXT("Text"),6);
DrawText(hdc,TEXT("Text"),0,LPRECT(0),0);

None of them shows a text on the screen. Drawing lines, ellipses, etc. works with no problems.

Why doesn't the above text-drawing routine work? Can anybody provide a working example?

Answer

Hans Passant picture Hans Passant · Sep 4, 2011

You are making the fairly classic mistake of not checking the return value of Graphics::DrawString(), it will tell you what you did wrong. InvalidParameter is pretty likely here. It is also quite unclear in which context this code runs, that better be inside the WM_PAINT message handler or you'll never see the output. There is also no evidence of cleanup code, as given the code leaks objects badly.

Let's work from a full example, starting from the boilerplate code generated by the Win32 Project template. I know you've got some of this already working but it could be interesting to others reading this answer. Start by giving the required #includes:

#include <assert.h>
#include <gdiplus.h>
using namespace Gdiplus;
#pragma comment (lib, "gdiplus.lib")

Locate the WinMain function, we need to initialize GDI+:

// TODO: Place code here.
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR           gdiplusToken;
Status st = GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
assert(st == Ok);
if (st != Ok) return FALSE;

and at the end of the function after the message loop:

GdiplusShutdown(gdiplusToken);
return (int) msg.wParam;

Now locate the window procedure (WndProc) and make the WM_PAINT case similar to this:

case WM_PAINT: {
    hdc = BeginPaint(hWnd, &ps);
    Graphics gr(hdc);
    Font font(&FontFamily(L"Arial"), 12);
    LinearGradientBrush brush(Rect(0,0,100,100), Color::Red, Color::Yellow, LinearGradientModeHorizontal);
    Status st = gr.DrawString(L"Look at this text!", -1, &font, PointF(0, 0), &brush);
    assert(st == Ok);
    EndPaint(hWnd, &ps);
} break;

Which produces this:

enter image description here

Modify this code as you see fit, the asserts will keep you out of trouble.