104上位机VC MFC设备上下文CDC绘制正弦曲线方法
104上位机VC MFC设备上下文CDC绘制正弦曲线方法
功能展示
绘制正弦曲线,在多媒体教学用的比较多,我们当前例程用设备上下文函数MoveTo(), LineTo()实现曲线的绘制;效果如图 要点提示 正弦曲线上,X坐标指定,Y的坐标可以通过公式 弧度=X坐标/曲线宽度*角系数*π ,Y坐标=振幅*曲线宽度*sin(弧度)来计算获得,计算中用到radian()函数,此函数的使用须包含基所在的头文件,文件#include <math.h>
实现功能 1.新建基于对话框的应用程序
2.在主对话框中的绘制函数OnPaint()中实现曲线的绘制 - if(!m_bDraw)
- return;
- //
- CDC *pDC = GetDC();
- //建立画笔
- CPen cpen,pen;
- pen.CreatePen(PS_SOLID,4,RGB(0,255,0));
- cpen.CreatePen(PS_SOLID,2,RGB(0,0,255));
- pDC->SelectObject(&cpen);
- //指定原点
- pDC->SetViewportOrg(100,245);
- pDC->SetTextColor(RGB(255,0,0));
- //绘制横坐标
- CString sPIText[]={"-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->TextOut(60*n-sPIText[n+1].GetLength()*3,16,sPIText[n+1]);
- }
- //
- pDC->MoveTo(0,0);
- CString sTmp;
- //绘制纵坐标
-
复制代码- for(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->TextOut(10,60*n,sTmp);
- }
- //绘制正弦网线
- double y,radian;
- pDC->SelectObject(&pen);
- for(int x=-60;x<600;x++)
- {
- //弧度=X坐标/曲线宽度*角系数*π
- //Y坐标=振幅*曲线宽度*sin(弧度)
- radian =x/((double)60*2)*PI;
- y=sin(radian)*2*60;
- pDC->MoveTo((int)x,(int)y);
- pDC->LineTo((int)x,(int)y);
- }
- cpen.DeleteObject();
- pen.DeleteObject();
- ReleaseDC(pDC);
复制代码其中变量m_bDraw为爱控变量,标识 是否绘制曲线
我们来演示下功能实现的整个过程
|