CImage通过WinApi的SetWorldTransform来实现图片旋转

SetWorldTransform的功能是旋转画布,这样产生的效果就是图像旋转。因此,在旋转画布之前,要把要旋转的图像的位置和大小准备好,这样旋转之后,才能使图像正好出现在显示区域内。这需要计算两个关键参数,图像的左上角坐标和旋转中心坐标。因为是固定大小旋转,因此我们将中心设定在图像的显示中心。这样需要计算选中图像的高和宽。

如下图:

具体实现方法如下:

cpp 复制代码
void ImageRotation(CImage* dst, const CImage* src, double angle)
{
	// 计算弧度
	angle = angle * PI / 180;

	// 获取图像宽度和高度
	int width = src->GetWidth();
	int height = src->GetHeight();

	// 计算旋转后的图像大小,并调整目标图像尺寸
	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);

	dst->Create(newWidth, newHeight, src->GetBPP());

	CPoint centerPt;
	CRect rect;
	rect.SetRect(0, 0, dst->GetWidth(), dst->GetHeight());
	centerPt.x = (rect.left + rect.right) / 2;
	centerPt.y = (rect.top + rect.bottom) / 2;

	// 获取源图像和目标图像的设备上下文对象
	CImageDC hdcSource(*src);
	CImageDC hdcDest(*dst);

	// 设置图形模式
	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 = (float)(centerPt.x - cos(angle)*centerPt.x + sin(angle)*centerPt.y);
	xform.eDy = (float)(centerPt.y - cos(angle)*centerPt.y - sin(angle)*centerPt.x);

	int nx, ny;
	nx = newWidth / 2 - width / 2;
	ny = newHeight / 2 - height / 2;

	// 进行旋转操作
	SetWorldTransform(hdcDest, &xform);
	CDC* pSrcDC = CDC::FromHandle(hdcSource);
	CDC* pDstDC = CDC::FromHandle(hdcDest);
	pDstDC->StretchBlt(nx, ny, src->GetWidth(), src->GetHeight(), pSrcDC, 0, 0, src->GetWidth(), src->GetHeight(), SRCCOPY);
}
相关推荐
序属秋秋秋40 分钟前
《C++初阶之内存管理》【内存分布 + operator new/delete + 定位new】
开发语言·c++·笔记·学习
千宇宙航7 小时前
闲庭信步使用图像验证平台加速FPGA的开发:第六课——测试图案的FPGA实现
图像处理·计算机视觉·fpga开发
十秒耿直拆包选手8 小时前
Qt:主窗体(QMainwindow)初始化注意事项
c++·qt
霖0010 小时前
C++学习笔记三
运维·开发语言·c++·笔记·学习·fpga开发
mit6.82410 小时前
[shad-PS4] Vulkan渲染器 | 着色器_重新编译器 | SPIR-V 格式
c++·游戏引擎·ps4
tan77º11 小时前
【Linux网络编程】Socket - TCP
linux·网络·c++·tcp/ip
Mike_Zhang12 小时前
C++使用WinHTTP访问http/https服务
c++
CHANG_THE_WORLD12 小时前
「macOS 系统字体收集器 (C++17 实现)」
开发语言·c++·macos
GiraKoo13 小时前
【GiraKoo】Breakpad 崩溃分析系统
c++
妄想出头的工业炼药师13 小时前
python和C++相互调用使用
开发语言·c++