背景
GDI+ 中使用 Graphics 类的成员函数 DrawImage 来绘制图片。
原样绘制
使用 Graphics 类的 成员函数 DrawImage 来绘制图片,当仅指定绘制起始位置时按照图片大小原样绘制。
void DemoGDI::DrawUser(HDC hdc)
{
Graphics graphics(hdc);//构造 Graphics 对象
SolidBrush solidBrush(Color::Green);
Image m_img(L"temp.png");
graphics.DrawImage(&m_img, 20, 20);
}
图片缩放
DrawImage 还可以指定要绘制图片区域的宽度和高度,实现图片的缩放绘制。
void DemoGDI::DrawUser(HDC hdc)
{
Graphics graphics(hdc);//构造 Graphics 对象
SolidBrush solidBrush(Color::Green);
Image m_img(L"temp.png");
graphics.DrawImage(&m_img, 0, 0,m_img.GetWidth()*0.3,m_img.GetHeight()*0.3);//缩小
graphics.TranslateTransform(100, 0);
graphics.DrawImage(&m_img, 0, 0, m_img.GetWidth()*1.2, m_img.GetHeight()*1.2);//放大
}
图片裁剪
DrawImage 还可以指定图片显示区域以及图像截取的范围,实现对指定区域的裁剪绘制和缩放。
void DemoGDI::DrawUser(HDC hdc)
{
Graphics graphics(hdc);//构造 Graphics 对象
SolidBrush solidBrush(Color::Green);
Image m_img(L"temp.png");
{//原样裁剪
graphics.DrawImage(&m_img, 20, 20, 0, 0, m_img.GetWidth(), m_img.GetHeight()*0.5, UnitPixel);
}
graphics.TranslateTransform(0, 200);
{//裁剪后缩放
graphics.DrawImage(&m_img, Rect(20, 20, 100, 100), 0, 0, m_img.GetWidth(), m_img.GetHeight()*0.5, UnitPixel);
}
}
图片旋转
Image 类的旋转翻转成员函数 RotateFlip 可以对图片进行简单的旋转和翻转,如 90 度、180度等,参数是一系列枚举值。
void DemoGDI::DrawUser(HDC hdc)
{
Graphics graphics(hdc);//构造 Graphics 对象
SolidBrush solidBrush(Color::Green);
Image m_img(L"temp.png");
graphics.DrawImage(&m_img, 0, 0);
graphics.TranslateTransform(300, 0);
m_img.RotateFlip(Rotate90FlipNone);//旋转90度
graphics.DrawImage(&m_img, 0, 0);
}
图片投影
矩形图像绘制到一个平行四边形中,可用于立体投影面图的绘制,传入的点数必须是 3,代表平行四边形的3个顶点,依次为:左上角、右上角和左下角。
void DemoGDI::DrawUser(HDC hdc)
{
Graphics graphics(hdc);//构造 Graphics 对象
Image m_img(L"temp.png");
int width = m_img.GetWidth()*0.5;
int height = m_img.GetHeight()*0.5;
int left = 50, top = 100;
//绘制正面
{
Point destPoints[] = { Point(left,top),Point(left + width,top),Point(left,top + height) };
graphics.DrawImage(&m_img, destPoints, 3);
}
//上面投影
{
Point destPoints[] = { Point(left+width*0.5,top-height*0.5),Point(left + width+width*0.5,top - height*0.5),Point(left,top ) };
graphics.DrawImage(&m_img, destPoints, 3);
}
//侧面投影
{
Point destPoints[] = { Point(left + width,top),Point(left + width + width*0.5,top - height*0.5),Point(left+width,top + height) };
graphics.DrawImage(&m_img, destPoints, 3);
}
}
设置透明色
通过ImageAttributes 类的SetColorKey方法可以指定透明颜色范围,图片中颜色在该范围的的像素将设置为透明色。
void DemoGDI::DrawUser(HDC hdc)
{
Graphics graphics(hdc);//构造 Graphics 对象
SolidBrush solidBrush(Gdiplus::Color(10,0,0,255));//背景颜色
Image m_img(L"temp.png");
graphics.FillRectangle(&solidBrush, 0, 0, m_img.GetWidth(), m_img.GetHeight());
Gdiplus::ImageAttributes ImAtt;
ImAtt.SetColorKey(Gdiplus::Color(250, 250, 250), Gdiplus::Color(255, 255, 255), Gdiplus::ColorAdjustTypeDefault);
graphics.DrawImage(&m_img,Rect( 0, 0, m_img.GetWidth(), m_img.GetHeight()),0,0, m_img.GetWidth(), m_img.GetHeight(), UnitPixel,&ImAtt);
}