1. 程式人生 > >C++開發-繪製正弦曲線

C++開發-繪製正弦曲線

通過OnDraw函式繪製圖形

過程為先繪製兩個座標軸,再繪製正弦曲線的方法。其中將曲線分解為660個畫素點,讓其看起來更像“曲線”

void CMFCApplication3View::OnDraw(CDC* pDC)
{
	CMFCApplication3Doc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);
	if (!pDoc)
		return;
	CPen cpen, pen;
	pen.CreatePen(PS_DASH, 4, RGB(0, 0, 0));      //建立畫筆
	cpen.CreatePen(PS_DASH, 2, RGB(0, 0, 255));
	pDC->SelectObject(&cpen);                     
	pDC->SetViewportOrg(200, 345);       //指定原點
	pDC->SetTextColor(RGB(255, 0, 0));
	CString sPITEX[] = { "-1/2π","","1/2π","π","3/2π","2π","5/2π","3π","7/2π","4π","9/2π","5π" };
	for (int n = -1, nTmp = 0; nTmp < 660; n++, nTmp += 60) {
		pDC->LineTo(60 * n, 0);
		pDC->LineTo(60 * n, -5);
		pDC->MoveTo(60 * n, 0);
		pDC->TextOutA(60 * n - sPITEX[n + 1].GetLength() * 3, 16, sPITEX[n + 1]);
	}
	pDC->MoveTo(0, 0);
	CString sTmp;
	for (int n = -4, nTmp = 0; nTmp <= 180; n++, nTmp = 60 * n) {
		pDC->LineTo(0, 60 * n);
		pDC->LineTo(5, 60 * n);
		pDC->MoveTo(0, 60 * n);
		sTmp.Format("%d", -n);
		pDC->TextOutA(10, 60 * n, sTmp);
	}
	double y, radian;
	pDC->SelectObject(&pen);
	for (int x = -60; x < 600; x++) {
		radian = x / ((double)60 * 2)*3.1415;
		y = sin(radian) * 2 * 60;
		pDC->MoveTo((int)x, (int)y);
		pDC->LineTo((int)x, (int)y);
	}
	cpen.DeleteObject();
	pen.DeleteObject();
	// TODO: 在此處為本機資料新增繪製程式碼
}