一、需求
本文介紹一些簡單畫圖的功能函數。
二、界面
主界面爲對話框,有最小化、最大化、關閉等功能。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。這個庫筆者十年前用過,如今一直在更新。