基于VC.NET的GDI+图像处理(2)
3.DrawImage方法
DrawImage是GDI+的Graphics类显示图像的核心方法,它的重载函数有许多个。常用的一般重载函数有:
Status DrawImage( Image* image, INT x, INT y);
Status DrawImage( Image* image, const Rect& rect);
Status DrawImage( Image* image, const Point* destPoints, INT count);
Status DrawImage( Image* image, INT x, INT y, INT srcx, INT srcy,
INT srcwidth, INT srcheight, Unit srcUnit);
其中,(x,y)用来指定图像image显示的位置,这个位置和image图像的左上角点相对应。rect用来指定被图像填充的矩形区域, destPoints和count分别用来指定一个多边形的顶点和顶点个数。若count为3时,则表示该多边形是一个平行四边形,另一个顶点由系统自动给出。此时,destPoints中的数据依次对应于源图像的左上角、右上角和左下角的顶点坐标。srcx、srcy、srcwidth 和srcheight用来指定要显示的源图像的位置和大小,srcUnit用来指定所使用的单位,默认时使用PageUnitPixel,即用像素作为度量单位。
调用和显示图像文件
在GDI+中调用和显示图像文件是非常容易的,一般先通过Image或Bitmap调入一个图像文件构造一个对象,然后调用Graphics::DrawImage方法在指定位置处显示全部或部分图像。例如下面的代码:
void CEx_GDIPlusView::OnDraw(CDC* pDC)
{
CEx_GDIPlusDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
using namespace Gdiplus;
Graphics graphics( pDC->m_hDC );
Image image(L"sunflower.jpg");
graphics.DrawImage(&image, 10,10);
Rect rect(130, 10, image.GetWidth(), image.GetHeight());
graphics.DrawImage(&image, rect);
}
结果如图7.17所示,从图中我们可以看出,两次DrawImage的结果是不同的,按理应该相同,这是怎么一回事?原来,DrawImage在不指定显示区域大小时会自动根据设备分辨率进行缩放,从而造成显示结果的不同。
当然,也可以使用Bitmap类来调入图像文件来构造一个Bitmap对象,其结果也是一样的。例如,上述代码可改为:
Bitmap bmp(L"sunflower.jpg");
graphics.DrawImage(&bmp, 10,10);
Rect rect(130, 10, bmp.GetWidth(), bmp.GetHeight());
graphics.DrawImage(&bmp, rect);
需要说明的是,Image还提供GetThumbnailImage的方法用来获得一个缩略图的指针,调用DrawImage后可将该缩略图显示,这在图像预览时极其有用。例如下面的代码:
Graphics graphics( pDC->m_hDC );
Image image(L"sunflower.jpg");
Image* pThumbnail = image.GetThumbnailImage(50, 50, NULL, NULL);
// 显示缩略图
graphics.DrawImage(pThumbnail, 20, 20);
// 使用后,不要忘记删除该缩略图指针
delete pThumbnail;
- 上一篇:清理VC工程
- 下一篇:深入浅出VC++串口编程之短信应用开发