在MFC当中,所有与作图相关的操作,MFC提供这样的一种类 CDC
1.首先创建一个单文档视图(Draw),实现划线功能
那么首先需要两个点,采用在视图类中添加消息WM_LButtonDown,那么这个消息
就是在鼠标左键按下之后,它就传递了一个点的参数CPoint point (CPoint是一个点类)
就可在视图类中添加一个CPoint类的变量 设为m_ptOrigin 权限设为private
i: 在构造函数中把这个点初始化: m_ptOrigin=0;
在点击左键的消息函数中
把这个点给保存下来,m_ptOrigin=point
void CDrawView::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
// MessageBox("View clicked");
m_ptOrigin=m_pOld=point;
CView::OnLButtonDown(nFlags, point);ii: 还有一个终点就是鼠标抬起时的响应 ,添加消息WM_LBUUTONUP,在其函数中添加
void CDrawView::OnLButtonUp(UINT nFlags, CPoint point)
{
/*HDC hdc;
hdc=::GetDC(m_hWnd);//我们用全局的GETDC,否则的话它就会认为你引用的是从CWnd派生出来的类的内部的成员函数了
MoveToEx(hdc,m_ptOrigin.x,m_ptOrigin.y,NULL);
LineTo(hdc,point.x,point.y);
::ReleaseDC(m_hWnd,hdc);//一定要释放DC
CView::OnLButtonUp(nFlags, point);
*/
//--------------------------------
CDC *pDC=GetDC();
pDC->MoveTo(m_ptOrigin);
pDC->LineTo(point);
ReleaseDC(pDC);
}其中参数point 为终点GetDC()函数是CWnd类的成员函数,不用作用域
MoveTo 和LineTo 都是CDC类的成员函数
作完图之后一定要释放DC
2.第二种:类CClientDC 解释:
The CClientDC class is derived from CDC and takes care of calling the Windows functionsGetDC at
construction time andReleaseDC at destruction time
也就是说它的基类是CDC,并且在构造其间已经完成获取和释放DC,不用再做操作
CClientDC dc(this);//this 得到的是view类的指针
// CClientDC dc(GetParent());//得到的是主框架的指针,但也只能在客户区域画线
// CWindowDC dc(GetDesktopWindow());//得到Windows窗口的指针
dc.MoveTo(m_ptOrigin);
dc.LineTo(point);
就像C++一样,每一个类它都有一个this 指针,这里可以得到视图类的指针
当然还有CWindowDC:::::::the CWindowDC class is derived from CDC. It calls the Windows
functionsGetWindowDC at construction time andReleaseDC at destruction time
注:这里有客户区和非客户区
主框架的客户区(视图+工具栏)非客户区(标题栏+菜单)
视图 没有非客户区,整个都 是客户区
3.画笔的属性:CPen 类,它封装了画笔的相关属性,就是可以自定义画笔
构造函数:CPen( int nPenStyle, int nWidth, COLORREF crColor );
第一个参数是画笔风格,二是宽度,三是Contains an RGB color for the pen.一个宏RGB里边
有三个参数表示不同的颜色
COLORREF RGB( BYTE byRed, // red component of color BYTE byGreen, // green component of color BYTE byBlue // blue component of color );在Buttonup函数中添加:
CPen pen(PS_SOLID,12,RGB(100,255,200));
CClientDC dc(this);
CPen *pOldPen=dc.SelectObject(&pen);//将这个笔选 到设备描述表当中,这样才会有效
dc.MoveTo(m_ptOrigin);
dc.LineTo(point);
dc.SelectObject(pOldPen);//一定要把画笔还原到设备描述表当中,否则指针还是你刚申请的!
注:selectobject()函数
CPen* SelectObject( CPen* pPen );返回值含义:
A pointer to the object being replaced. This is a pointer to an object of one of the classes derived from CGdiObject, such as CPen, depending on which version of the function is used. The return value is NULL if there is an error. This function may return a pointer to a temporary object. This temporary object is only valid during the processing of one Windows message。
也就是说它的返回值是一个替换的,不是原来 的。我们把一个新的画笔的选择到设备描述表当中时,
它不会把设备描述表中先前的对象给你返回回来,然而若不还原原来 的对象指针,那么在其它的地方用的
就是所选到设备描述表当中的新的画笔,所以,在作画图时,会把原来的画笔不愿回来!!!
149

被折叠的 条评论
为什么被折叠?



