繪圖基礎--橡皮筋畫線

繪圖基礎--橡皮筋畫線

橡皮筋畫線:用戶點擊鼠標左鍵定下一個起點,然後把鼠標拖到目標終點,這時程序就會在起始點間畫線。


// rubber.cpp

#include <afxwin.h>

// Define the application class
class CApp : public CWinApp
{
public:
	virtual BOOL InitInstance();
};

CApp App;  

// Define the window class
class CWindow : public CFrameWnd
{ 
	HCURSOR cross;
	HCURSOR arrow;
	CPoint start, old;
	BOOL started;
public:
	CWindow(); 
	afx_msg void OnMouseMove(UINT,CPoint);
	afx_msg void OnLButtonDown(UINT, CPoint);
	afx_msg void OnLButtonUp(UINT, CPoint);
	DECLARE_MESSAGE_MAP()
};

// The window constructor
CWindow::CWindow()
{ 
	// Load two cursors
	cross = AfxGetApp()->LoadStandardCursor(IDC_CROSS);
	arrow = AfxGetApp()->LoadStandardCursor(IDC_ARROW);
	started=FALSE;
	
	// Create a custom window class
	const char* pszWndClass = AfxRegisterWndClass(
		CS_HREDRAW | CS_VREDRAW, NULL,
		(HBRUSH)(COLOR_WINDOW+1), NULL);
	
	// Create the window
	Create(pszWndClass, "Drawing Tests", 
		WS_OVERLAPPEDWINDOW,
		CRect(0,0,250,250)); 
}

// The message map
BEGIN_MESSAGE_MAP( CWindow, CFrameWnd )
	ON_WM_MOUSEMOVE()	
	ON_WM_LBUTTONDOWN()
	ON_WM_LBUTTONUP()
END_MESSAGE_MAP()

// Start a new line when the user clicks
// the mouse button down
void CWindow::OnLButtonDown(UINT flag,
	CPoint mousePos)
{
	started = TRUE;
	::SetCursor(cross);
	// save the starting position of the line
	start = old = mousePos;
	CClientDC dc(this);
	dc.SetROP2(R2_NOT);
	dc.MoveTo(start);
	dc.LineTo(old);
}

// Complete the line when the user releases
// the mouse button
void CWindow::OnLButtonUp(UINT flag,
	CPoint mousePos)
{
	if (started)
	{
		started = FALSE;
		::SetCursor(arrow);
		CClientDC dc(this);
		dc.MoveTo(start);
		dc.LineTo(old);
	}
}

// Handle dragging
void CWindow::OnMouseMove(UINT flag,
	CPoint mousePos)
{
	// If the mouse button is down and there
	// is a line in progress, rubber band
	if ((flag == MK_LBUTTON) && started)
	{
		::SetCursor(cross);
		CClientDC dc(this);
		dc.SetROP2(R2_NOT);
		// Undraw the old line
		dc.MoveTo(start);
		dc.LineTo(old);
		// Draw the new line
		dc.MoveTo(start);
		dc.LineTo(mousePos);
		old=mousePos;
	}
	else
		::SetCursor(arrow);
}

// Init the application
BOOL CApp::InitInstance()
{
	m_pMainWnd = new CWindow();
	m_pMainWnd->ShowWindow(m_nCmdShow);
	m_pMainWnd->UpdateWindow();
	return TRUE;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章