绘制思路:做一个自定义控件插入界面中
具体步骤:
(1)横轴划分为若干点,使用Moveto+Lineto连线,定时刷新实现动态效果;
(2)在程序中,使用CPaintDC,CClientDc,CDC,CBitMap,CBrush等绘图类;
(3)绘图程序分为几大部分:注册类句柄、刷新机制、设定坐标系、绘图;
部分代码如下:
BOOL CLineChartCtrl::RegisterWndClass(HINSTANCE hInstance)
{
WNDCLASSW wc;
wc.lpszClassName = TEXT("LineChartCtrl"); // matches class name in client
。。。
return (::RegisterClass(&wc) != 0 ); }
void CLineChartCtrl::InvalidateCtrl()
{
CClientDC dc(this);
CRect rcClient;
GetClientRect(rcClient);
if (m_MemDC.GetSafeHdc() == NULL)
{
m_MemDC.CreateCompatibleDC(&dc);
m_Bitmap.CreateCompatibleBitmap(&dc,rcClient.Width(),rcClient.Height());
m_MemDC.SelectObject(m_Bitmap);
m_MemDC.SetBkColor(RGB(255,255,255)); //静态背景色
CBrush bkBrush(RGB(160,160,160));
m_MemDC.FillRect(rcClient,&bkBrush);
}
InvalidateRect(rcClient, FALSE);
}
float CLineChartCtrl::SetPos(int nIndex, float nPos)
{
。。。}
void CLineChartCtrl::OnPaint()
{
CPaintDC dc(this); // device context for painting
CRect rcClient;
GetClientRect(rcClient);
// draw scale
if (m_MemDC.GetSafeHdc() != NULL)
dc.BitBlt(0, 0, rcClient.Width(), rcClient.Height(), &m_MemDC, 0, 0, SRCCOPY);
}
void CLineChartCtrl::DrawSpike()
{
CRect rcClient;
GetClientRect(rcClient);
if (m_MemDC.GetSafeHdc() != NULL) //竖线间隔宽度
{
m_MemDC.BitBlt(0, 0, rcClient.Width(), rcClient.Height(), &m_MemDC, 20, 0, SRCCOPY);
// draw scale
CRect rcRight = rcClient;
rcRight.left = rcRight.right - 20;
m_MemDC.SetBkColor(RGB(255,255,255)); //运行时背景色
CBrush bkBrush(RGB(160,160,160));
m_MemDC.FillRect(rcRight,&bkBrush);
static BOOL bDrawVerticle = FALSE;
bDrawVerticle = !bDrawVerticle;
if (bDrawVerticle)
{
CPen pen(PS_SOLID, 1, RGB(128,128,128)); //纵轴色
CPen* pOldPen = m_MemDC.SelectObject(&pen);
m_MemDC.MoveTo(CPoint(rcClient.right-2, rcClient.top));
m_MemDC.LineTo(CPoint(rcClient.right-2, rcClient.bottom));
m_MemDC.SelectObject(pOldPen);
}
int nCount = m_items.GetSize();
CLineChartItem* pItem;
CPoint ptOld, ptNew;
for (int i="0"; i<nCount; i++)
{
pItem = m_items.GetAt(i);
float nRange = pItem->m_nUpper - pItem->m_nLower;
ptOld.x = rcRight.left-1; // Minus one to make sure to draw inside the area
ptNew.x = rcRight.right-1;
ptOld.y = (int)((((float)(nRange - pItem->m_nOldPos))/(float)nRange)
* (float)rcRight.Height());
ptNew.y = (int)((((float)(nRange - pItem->m_nPos))/(float)nRange)
* (float)rcRight.Height());
CPen pen(PS_SOLID, 1, pItem->m_colorLine);
CPen* pOldPen = m_MemDC.SelectObject(&pen);
m_MemDC.MoveTo(ptOld);
m_MemDC.LineTo(ptNew);
m_MemDC.SelectObject(pOldPen);
}
}
}
BOOL CLineChartCtrl::Add(COLORREF color, float Upper, float Lower)
{
CLineChartItem* pItem = new CLineChartItem;
pItem->m_colorLine = color;
pItem->m_nLower = Lower;
pItem->m_nUpper = Upper;
pItem->m_nPos = 0;
pItem->m_nOldPos = 0;
try
{
m_items.Add(pItem);
InvalidateCtrl();
return TRUE;
}
catch (CMemoryException* e)
{
if (pItem !=NULL)
delete pItem;
e->Delete();
return FALSE;
}
}
void CLineChartCtrl::Go()
{
DrawSpike();
Invalidate(FALSE);
}
文章评论(0条评论)
登录后参与讨论