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


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

    具体实现方法如下:

    1. void ImageRotation(CImage* dst, const CImage* src, double angle)
    2. {
    3. // 计算弧度
    4. angle = angle * PI / 180;
    5. // 获取图像宽度和高度
    6. int width = src->GetWidth();
    7. int height = src->GetHeight();
    8. // 计算旋转后的图像大小,并调整目标图像尺寸
    9. int newWidth = static_cast<int>(abs(cos(angle)) * width + abs(sin(angle)) * height);
    10. int newHeight = static_cast<int>(abs(sin(angle)) * width + abs(cos(angle)) * height);
    11. if (!dst->IsNull())
    12. {
    13. dst->Destroy();
    14. }
    15. dst->Create(newWidth, newHeight, src->GetBPP());
    16. CPoint centerPt;
    17. CRect rect;
    18. rect.SetRect(0, 0, dst->GetWidth(), dst->GetHeight());
    19. centerPt.x = (rect.left + rect.right) / 2;
    20. centerPt.y = (rect.top + rect.bottom) / 2;
    21. // 获取源图像和目标图像的设备上下文对象
    22. CImageDC hdcSource(*src);
    23. CImageDC hdcDest(*dst);
    24. // 设置图形模式
    25. SetGraphicsMode(hdcDest, GM_ADVANCED);
    26. // 保存旋转数据的结构体
    27. XFORM xform;
    28. xform.eM11 = static_cast(cos(angle));
    29. xform.eM12 = static_cast(sin(angle));
    30. xform.eM21 = static_cast(-sin(angle));
    31. xform.eM22 = static_cast(cos(angle));
    32. xform.eDx = (float)(centerPt.x - cos(angle)*centerPt.x + sin(angle)*centerPt.y);
    33. xform.eDy = (float)(centerPt.y - cos(angle)*centerPt.y - sin(angle)*centerPt.x);
    34. int nx, ny;
    35. nx = newWidth / 2 - width / 2;
    36. ny = newHeight / 2 - height / 2;
    37. // 进行旋转操作
    38. SetWorldTransform(hdcDest, &xform);
    39. CDC* pSrcDC = CDC::FromHandle(hdcSource);
    40. CDC* pDstDC = CDC::FromHandle(hdcDest);
    41. pDstDC->StretchBlt(nx, ny, src->GetWidth(), src->GetHeight(), pSrcDC, 0, 0, src->GetWidth(), src->GetHeight(), SRCCOPY);
    42. }

    该方法优点是速度快,比我之前写的双循环遍历像素点,对图片进行旋转要快得多。

    我用来测试的jpg图片的分辨率是3456*4806,之前的遍历像素点方法用时是1700多毫秒,而上面的方法用时是600多毫秒,可见效果很明显了。

    PS:我一开始用SetWorldTransform,旋转后,图像无法定位到正确的地方,还好借鉴了一个大佬的文章,连接在下方。

    图片浏览器开发日志-05(显示速度)_setworldtransform 后显示慢-CSDN博客

  • 相关阅读:
    【JS红宝书学习笔记】第6章 集合引用类型
    微服务【Ribbon负载均衡&源码解析&饥饿加载】第2章
    【C/C++】STL——容器适配器:stack和queue的使用及模拟实现
    【PowerMockito:编写单元测试过程中原方法没有注入的属性在跑单元测试时出现空指针】
    Spring 框架知识点汇总 (持续更新)
    【手写数字识别】GPU训练版本
    企业为什么做不好生产计划?
    java异常类如何定义
    html + thymeleaf 制作邮件模板
    头部咨询管理企业的数字化转型之路
  • 原文地址:https://blog.csdn.net/u014385680/article/details/134504835