c++ - 获取可调整大小的选择区域的 QTransform
问题描述
我构建了一个小的自定义 qml 项目,用作选择区域(类似于Qt Widgets 中提供的QRubberBand组件)。该项目还使用户能够调整选择内容的大小,因此通过抓住选择矩形的底角,可以拖动以放大内容。用户完成调整大小后,我想计算转换的QTransform
矩阵。QTransform
提供了一个方便的QTransform::scale方法来获得一个比例变换矩阵(我可以通过将宽度和高度比与之前的选择大小进行比较来使用)。问题是QTransform::scale
假设转换的中心点是对象的中心,但我希望我的转换原点位于选择的左上角(因为用户从右下角拖动)。
例如,如果我有以下代码:
QRectF selectionRect = QRectF(QPointF(10,10), QPointF(200,100));
// let's resize the rectangle by changing its bottom-right corner
auto newSelectionRect = selectionRect;
newSelectionRect.setBottomRight(QPointF(250, 120));
QTransform t;
t.scale(newSelectionRect.width()/selectionRect.width(), newSelectionRect.height()/selectionRect.height());
这里的问题是,如果我将转换t
应用于我的原始selectionRect
我没有得到我的新矩形newSelectionRect
,但我得到以下内容:
QRectF selectionRect = QRectF(QPointF(10,10)*sx, QPointF(200,100)*sy);
其中sx
和sy
是变换的比例因子。我想要一种方法来计算QTransform
我的转换newSelectionRect
在应用于selectionRect
.
解决方案
问题在于这个假设:
QTransform::scale 假设变换的中心点是物体的中心
QTransform 执行的所有变换都参考轴的原点,只是各种变换矩阵的应用(https://en.wikipedia.org/wiki/Transformation_matrix):
此外,QTransform::translate ( https://doc.qt.io/qt-5/qtransform.html#translate ) 指出:
沿 x 轴移动坐标系 dx,沿 y 轴移动 dy,并返回对矩阵的引用。
因此,您正在寻找的是:
QTransform t;
t.translate(+10, +10); // Move the origin to the top left corner of the rectangle
t.scale(newSelectionRect.width()/selectionRect.width(), newSelectionRect.height()/selectionRect.height()); // scale
t.translate(-10, -10); // move the origin back to where it was
QRectF resultRect = t.mapRect(selectionRect); // resultRect == newSelectionRect!
推荐阅读
- elasticsearch - ES_dsl.Q() 中“路径”的功能是什么?
- sql - 有没有办法从 SQL 中的一组列中获取所有非空值?
- python - 在 Jupyter 笔记本中重新加载 Python 模块(不自动重新加载)
- android - 快速启动状态选择后模拟器关闭
- javascript - 在单文件组件方法中使用 vue-styled-components
- ios - 与文本字段的用户默认值比较
- angular - 然后如何以角度2返回Promise的数据
- php - 教义 - 实体侦听器中注入实体之间的区别
- python - 加快python图像颜色阈值/过滤
- javascript - Babel 7 Jest Core JS “TypeError:wks 不是函数”