一.画一个红色边框的矩形
创建一个MFC实例,选择基于对话框.其他默认.
在CTestDlg3Dlg类中找到,OnPaint()函数
在else后面添加如下语句,注意:加在CDialog::OnPaint();后面.
CClientDC dc( this ); //取设备
CPen pen; // 定义画笔
pen.CreatePen( PS_SOLID,10,RGB(255,0,0) ); //创建画笔类型
dc.SelectObject ( pen ); //设备上选择画笔对象
dc.MoveTo( 0,0 );
dc.LineTo( 100,0 );
dc.LineTo( 200,200 );
dc.LineTo( 200,200 );
二.画一个带三维效果的矩形框
创建一个CMyButton类
结果如下:
申明部分(MyButton.h):
class CMyButton
{
public:
int x0,y0; //起始点坐标
int w,h; //矩形的宽度和高度
int thick; //三维效果厚度
COLORREF clr; //填充色彩
void draw( CClientDC* ); //绘制函数
CMyButton();
CMyButton(int,int,int,int); //构造函数
virtual ~CMyButton();
};
定义部分(Mybutton.cpp):
// MyButton.cpp: implementation of the CMyButton class.
//
//
#include "stdafx.h"
#include "testDlg3.h"
#include "MyButton.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//
// Construction/Destruction
//
CMyButton::CMyButton()
{
}
CMyButton::CMyButton(int x1,int y1,int w1,int h1)
{
x0 = x1;
y0 = y1;
w = w1;
h = h1;
}
CMyButton::~CMyButton()
{
}
void CMyButton::draw( CClientDC *dc)
{
CRect rect(x0,y0,w+x0,h+y0); // 创建矩形对象
CBrush brush; // 创建画刷对象
brush.CreateSolidBrush( clr );
dc->FillRect( &rect, &brush);
CPen lightPen;
lightPen.CreatePen( PS_SOLID,thick,RGB(200,255,200) );
dc->SelectObject( lightPen );
dc->MoveTo( x0+w,y0 );
dc->LineTo( x0,y0 );
dc->LineTo( x0,y0+h);
CPen darkPen;
darkPen.CreatePen( PS_SOLID,thick,RGB(10,20,20) );
dc->SelectObject( darkPen );
dc->MoveTo( x0,y0+h );
dc->LineTo( x0+w,y0+h );
dc->LineTo( x0+w,y0);
}
类的调用方式:
同样是在CTestDlg3Dlg类中找到,OnPaint()函数
在else后面添加如下语句,
CDialog::OnPaint();
CClientDC dc( this );
CMyButton btn(50,50,100,50);
btn.clr = RGB(155,200,155);
btn.thick=3;
btn.draw( &dc );
在VC6.0中使用GDI+双缓冲高效绘图
在前面的“VC/MFC 高效绘图--双缓冲”这篇文章,介绍了VC6.0中 使用GDI双缓冲绘图的方法,效果很显著。绘图效率成倍提高,刷新时,屏幕基本上不会闪烁。
随着Microsoft 推出DotNET平台,微软的绘图引擎GDI也升级到GDI+。GDI+带来了全新的感受,图形和文字的轮廓更加平滑。使用方法较前者更为简单,效果也好了很多。
GDI+的特色为:渐变画刷,独立路径对象,矩阵对象,Alpha Blending,多格式图片支持等等。
既然GDI+比GDI优越了很多,为啥不用呢?.NET平台的VS2005可以直接使用,而VC6.0则需要下载PlatfromSDK,并配置。这在我的另外文章中将会详细介绍。
GDI可以实现双缓冲绘图,那GDI+自然可以了,但实现方法,网上非常之少,尤其是针对VC6.0的。我通过多方寻觅,百般试验,终于成功。说明如下:
Graphics g(pDC->m_hDC);//创建Graphics对象
Bitmap CacheImage(rect.Width(),rect.Height()); //依窗口大小创建内存画布
Graphics buffer(&CacheImage);//Gaphics对象引用内存画布
buffer.Clear(Color::White);//清除内存画布并以白色填充,当然也可以是其它颜色
Pen pen(Color::Red,1);//创建画笔
buffer.DrawLine(&pen,0,0,100,300);//在内存画布中绘画
g.DrawImage(&CacheImage, 0, 0);//将内存画布贴到屏幕。绘画结束