基于WTL的工程使用GdiPlus的简单步骤

发现并强调的一个地方:
带view的sdi工程,OnPaint函数在view文件中实现;不带view的在MainFrm中实现。

目前发现的gdiplus绘制不起作用的原因:
1.没有使用CPaintDC(BeginPaint(); EndPaint();获取窗口无效区域)
2.可能工程含有view文件,这时要在view文件中的OnPaint方法内实现,如果在MainFrm文件中写则不会work

【1】新建ATL/WTL工程-->SDI-->使用默认完成即可(包含了Rebar、CommandBar等组件和view文件,可以研究下代码)
【2】在Stdafx.h文件中添加代码:

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

【3】在主文件[工程名].cpp文件中定义结构体(非常方便):

struct using_gdiplus
{
    Gdiplus::GdiplusStartupInput gdiplusStartupInput;
    ULONG_PTR           gdiplusToken;

    using_gdiplus()
    {
        Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
    }
    ~using_gdiplus()
    {
        Gdiplus::GdiplusShutdown(gdiplusToken);
    }
};

并在main()方法中添加代码:

    using_gdiplus g;//here will be okay (for gdiplus to work)

    int nRet = Run(lpstrCmdLine, nCmdShow);  //原有代码
    ...    

【4】由于这个测试工程含view文件,所以在view文件的OnPaint()方法中添加代码:

    LRESULT OnPaint(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
    {
        CPaintDC dc(m_hWnd);

        //TODO: Add your drawing code here
        Graphics g(dc.m_hDC);

        RECT rcClient;
        GetClientRect(&rcClient);

        SolidBrush oBrush(Color::Red);
        /*g.FillRectangle(&oBrush, rcClient.left, rcClient.top, rcClient.right - rcClient.left, rcClient.bottom - rcClient.top);*/
        g.FillRectangle(&oBrush, 30,30, 300,300);
        return 0;
    }

DONE.

posted @ 2014-03-12 13:03  Tup  阅读(256)  评论(0)    收藏  举报