MFC Dynamic Curves: OnDraw Tutorial
To draw dynamic curves in MFC, you can achieve this by overriding the OnDraw function of the window class. The specific steps are as follows:
- In the header file of the Window class, define the data structure for the curve that needs to be drawn, for example:
class CMyView : public CView
{
// 曲线数据结构
CArray<CPoint, CPoint> m_points;
};
- Override the OnDraw function in the implementation file of the window class to draw a curve.
void CMyView::OnDraw(CDC* pDC)
{
CRect rect;
GetClientRect(&rect);
// 创建画笔
CPen pen(PS_SOLID, 2, RGB(0, 0, 255));
CPen* pOldPen = pDC->SelectObject(&pen);
// 绘制曲线
for (int i = 1; i < m_points.GetSize(); i++)
{
pDC->MoveTo(m_points[i - 1]);
pDC->LineTo(m_points[i]);
}
pDC->SelectObject(pOldPen);
}
- Add a function in the window class to update the curve data, and call this function when the curve needs to be updated.
void CMyView::AddPoint(CPoint point)
{
m_points.Add(point);
Invalidate();
}
- Call the AddPoint function where you need to draw a curve, and add a new data point.
void CMyView::OnMouseMove(UINT nFlags, CPoint point)
{
if (nFlags & MK_LBUTTON)
{
AddPoint(point);
}
}
This allows for the dynamic drawing of curves while the mouse moves.