Drawing Text with GDI+

99封情书 提交于 2019-11-30 21:56:58

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:

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

MSDN is your friend (true thing): Drawing a Line - code sample: compile and run and Drawing a String -- replace OnPaint() in previous one.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!