Drawing Text with GDI+

前端 未结 2 735
清酒与你
清酒与你 2020-12-18 04:10

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

相关标签:
2条回答
  • 2020-12-18 04:51

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

    0 讨论(0)
  • 2020-12-18 04:53

    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.

    0 讨论(0)
提交回复
热议问题