在 MFC 中使用 CImage 类加载图片并进行旋转的示例代码如下:
CImage image;
if (image.Load(_T("path_to_image.jpg")) == S_OK) {
// 获取图像宽度和高度
int width = image.GetWidth();
int height = image.GetHeight();
// 创建一个新的 CImage 对象用于存储旋转后的图像
CImage rotatedImage;
if (rotatedImage.Create(width, height, image.GetBPP()) == S_OK) {
// 设置旋转角度(以弧度为单位)
double angle = 45.0;
// 计算旋转后的图像大小,并调整目标图像尺寸
int newWidth = static_cast<int>(abs(cos(angle)) * width + abs(sin(angle)) * height);
int newHeight = static_cast<int>(abs(sin(angle)) * width + abs(cos(angle)) * height);
rotatedImage.Resize(newWidth, newHeight);
// 获取源图像和目标图像的设备上下文对象
HDC hdcSource = image.GetDC();
HDC hdcDest = rotatedImage.GetDC();
// 进行旋转操作
SetGraphicsMode(hdcDest, GM_ADVANCED);
XFORM xform;
xform.eM11 = static_cast<FLOAT>(cos(angle));
xform.eM12 = static_cast<FLOAT>(sin(angle));
xform.eM21 = static_cast<FLOAT>(-sin(angle));
xform.eM22 = static_cast<FLOAT>(cos(angle));
xform.eDx = 0.0f;
xform.eDy = 0.0f;
SetWorldTransform(hdcDest, &xform);
BitBlt(hdcDest, 0, 0, width, height, hdcSource, 0, 0, SRCCOPY);
// 释放设备上下文对象
image.ReleaseDC();
rotatedImage.ReleaseDC();
// 在指定的位置绘制旋转后的图像
CDC* pDC = GetDC();
rotatedImage.Draw(pDC->GetSafeHdc(), xPosition, yPosition);
}
}
请确保将 “path_to_image.jpg” 替换为实际的图片文件路径,并根据需要调整旋转角度和绘制位置。另外,还需要包含相应的头文件和链接相关库(如 Gdiplus.lib)以使用 CImage 类和图形操作函数。
内容由零声教学AI助手提供,问题来源于学员提问