MFC小笔记:简单画图

一、需求

本文介绍一些简单画图的功能函数。

二、界面

主界面为对话框,有最小化、最大化、关闭等功能。MFC基本原理不再介绍。

三、功能

画线

定义:

enum MYCOLOR
{
    WHITE = 0,
    GRAY = 1,
    LBLUE = 2,
    BLUE = 3,
};

CPen m_pen[5];

初始化画笔:

    DWORD dwBackColor = GetSysColor(CTLCOLOR_DLG);
    byte r = (dwBackColor >> 16) & 0xff;
    byte g = (dwBackColor >> 8) & 0xff;
    byte b = (dwBackColor >> 0) & 0xff;
    // 参数:样式、宽度、颜色
    m_pen[WHITE].CreatePen(PS_SOLID, 2, RGB(r, g, b));     // 背景色
    m_pen[GRAY].CreatePen(PS_SOLID, 2, RGB(99, 69, 96));     // 灰色
    m_pen[LBLUE].CreatePen(PS_SOLID, 2, RGB(51, 102, 205));     // 浅蓝
    m_pen[BLUE].CreatePen(PS_SOLID, 2, RGB(0, 0, 205));      // 蓝色 注:使用205,深一些

画线函数:

void CFoobar::Line(CDC *pDC, MYCOLOR color, int x1, int y1, int x2, int y2)
{
    pDC->MoveTo(x1, y1);
    pDC->LineTo(x2, y2);
//    Sleep(500);
}

画十字形和四边角:


void CFoobar::DrawCross(CDC *pDC, int x, int y, MYCOLOR color, bool bDraw)
{
    CPen *oldPen = pDC->SelectObject(&m_pen[GRAY]);//保存DC原始画笔
    int radius = 22;
    int basegap = 4;
    int rectradius = radius- basegap;
    int rectgap = 10;
    
    if (bDraw)
    {
        pDC->SelectObject(&m_pen[color]);
    }
    else
    {
        pDC->SelectObject(&m_pen[WHITE]);
    }
    // 十字形,上、下、左、右
    Line(pDC, color, x - radius, y, x - basegap, y);
    Line(pDC, color, x + basegap, y, x + radius, y);
    Line(pDC, color, x, y - radius, x, y - basegap);
    Line(pDC, color, x, y + basegap, x, y + radius);

    // 四边角,逆时针画
    Line(pDC, color, x - rectgap, y - rectradius, x - rectradius, y - rectradius);
    Line(pDC, color, x - rectradius, y - rectradius, x - rectradius, y - rectgap);
    Line(pDC, color, x - rectradius, y + rectgap, x - rectradius, y + rectradius);
    Line(pDC, color, x - rectradius, y + rectradius, x - rectgap, y + rectradius);
    Line(pDC, color, x + rectgap, y + rectradius, x + rectradius, y + rectradius);
    Line(pDC, color, x + rectradius, y + rectradius, x + rectradius, y + rectgap);
    Line(pDC, color, x + rectradius, y - rectgap, x + rectradius, y - rectradius);
    Line(pDC, color, x + rectradius, y - rectradius, x + rectgap, y - rectradius);

    pDC->SelectObject(oldPen);       //回复DC原画笔
}

注意,让画的线条“消失”有很多种方法,本文使用背景色重新画一次,以达到“消失”的目的。背景色获取使用 GetSysColor(CTLCOLOR_DLG) 得到。CTLCOLOR_DLG 为对话框控件,其它控件有 CTLCOLOR_BTN、CTLCOLOR_EDIT 等。
DrawCross 函数效果见地址: https://github.com/libts/tslib。这个库笔者十年前用过,如今一直在更新。

发布了481 篇原创文章 · 获赞 244 · 访问量 110万+

猜你喜欢

转载自blog.csdn.net/subfate/article/details/103651184