QPainter::scale
以窗口的左上角为原点。为了将窗口的中心用作原点,我想我可以先使用QPainter::translate
将坐标系的原点转换为窗口的中心,然后缩放图形:
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr) :
QMainWindow(parent) {
resize(600, 400);
}
protected:
void paintEvent(QPaintEvent *) override {
QPainter painter(this);
// draw a rectangle
QRectF rectangle(10.0, 20.0, 80.0, 60.0);
painter.drawRect(rectangle);
// translate the origin of coordinate system to the center of window
QPointF offset = rect().center();
painter.translate(offset);
// scale the rectangle
painter.scale(2,2);
painter.drawRect(rectangle);
}
};
该示例将产生以下结果:
问题是比例尺仍相对于左上角。
该如何解决?
以下是我的解决方案。
QPainter painter(this);
// draw a rectangle
QRectF rectangle1(10.0, 20.0, 80.0, 60.0);
painter.drawRect(rectangle1);
// scale the rectangle by 2 times
QRectF rectangle2(10.0, 20.0, 80.0 * 2, 60.0 * 2);
// move it to the center of window
QPointF offset = rect().center() - rectangle2.center();
painter.translate(offset);
painter.drawRect(rectangle2);
答案 0 :(得分:1)
您错过了一步,即在缩放比例之后重新转换画家。换句话说,在
painter.scale(2,2);
painter.drawRect(rectangle);
添加
painter.translate(-offset);
答案 1 :(得分:1)
找到适用于QPainter的适当变换并非一件容易的事,因为它涉及将一个元素居中放置,移动另一个等。最简单的方法是如下图所示变换矩形:
void Widget::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
// draw a rectangle
QRectF rectangle(10.0, 20.0, 80.0, 60.0);
painter.drawRect(rectangle);
// scale
rectangle.setSize(2*rectangle.size());
// translate
rectangle.moveCenter(rect().center());
painter.drawRect(rectangle);
}