C++ | GDI+绘制界面

536 阅读1分钟

「这是我参与11月更文挑战的第4天,活动详情查看:2021最后一次更文挑战」。

GDI: (Graphics Device Interfase)图形设备接口,是一个应用程序与输出设备之间的中介。

运行环境: Gdiplus.dll 包含在Windows系统中。【在system32中包含Gdiplus.dll文件】。

1.包含头文件: #include <Gdiplus.h>

2.链接库文件: 属性->配置->连接器->输入->附加依赖项->Gdiplus.lib;

3.定义成员变量: ULONG_PTR m_gdiplusToken;

4.在CMYAPP类的函数InitInstance()中加入:

        GdiplusStartupInput gdiplusStartupInput;

        GdiplusStartup(&m_gdiplusToken, &gdiplusStartupInput, NULL);

5.在CMYAPP类的函数ExitInstance()中加入:

        GdiplusShutdown(m_gdiplusToken);

6.一个Text属性结构体:

typedef struct{

        RectF rectF;//文字区域

        Color color;//文字颜色

        CString text;//文本

        int fontSize;//文字大小

        Gdiplus::StringAlignment styleX; //水平对齐方式

        Gdiplus::StringAlignment styleY; //垂直对齐方式

        Gdiplus::StringFormatFlags styleWrap; //是否换行

        int fontArial; //是否粗体

        CString fontStyle; //字体名称

}m_Text;

7.一个Image属性结构体:

typedef struct{

        RectF rectF;//图片区域

        CString szPath; //图片路径

}m_Image;

8.绘制文字:

Void SetGDIFont(m_Text text, HDC hdc)

{

        Graphics      graphics(hdc);

        SolidBrush    brush(text.color); //字体颜色

        FontFamily    fontFamily(text.fontStyle);

        Gdiplus::Font font(&fontFamily, text.fontSize, text.fontArial, UnitPixel);

        RectF         rectF(text.rectF);

        graphics.SetTextRenderingHint(TextRenderingHintAntiAlias); // 平滑处理

        StringFormat stringformat = new StringFormat;

        stringformat.SetAlignment(text.styleX);

        stringformat.SetLineAlignment(text.styleY);

        graphics.DrawString(text.text,-1,&font,rectF,&stringformat,&brush); //绘制

        graphics.ReleaseHDC(hdc);

}

9.绘制图片:

void SetGDIImage(m_Image image, HDC hdc)

{

        Graphics      graphics(hdc);

        Image image(szImagePath,FALSE);

        graphics.DrawImage(&image, image.rectF.left, image.rectF.top,

                 image.rectF.right-rectF.left, image.rectF.bottom-rectF.top); //绘制

        graphics.ReleaseHDC(hdc);

}