QPainter DrawImage 居中对齐

use*_*688 5 qt qpainter

有什么办法可以在QPainter居中对齐的情况下绘制图像吗?我看到QPainter::drawText给了我们这个规定,但drawImage没有。我有一个源矩形、目标矩形和一个图像。当源尺寸很小时,图像会被绘制在页面的左侧。我希望它打印居中对齐。

Rei*_*ica 7

画家没有尺码,但device()它画的尺码有。您可以将其QRect(painter.device()->width(), painter.device()->height())用作要将图像居中的矩形。

然后你可以像这样将图像居中绘制:

QImage source;
QPainter painter(...);
...
QRect rect(source.rect());
QRect devRect(0, 0, painter.device()->width(), painter.device()->height());
rect.moveCenter(devRect.center());
painter.drawImage(rect.topLeft(), source);
Run Code Online (Sandbox Code Playgroud)


vah*_*cho 2

我会尝试执行以下操作(请遵循源代码注释):

应该绘制的示例图像

// The image to draw - blue rectangle 100x100.
QImage img(100, 100, QImage::Format_ARGB32);
img.fill(Qt::blue);
Run Code Online (Sandbox Code Playgroud)

在绘制事件处理程序中

[..]
QRect source(0, 0, 100, 100);
QRect target(0, 0, 400, 400);

// Calculate the point, where the image should be displayed.
// The center of source rect. should be in the center of target rect.
int deltaX = target.width() - source.width();
int deltaY = target.height() - source.height();

// Just apply coordinates transformation to draw where we need.
painter.translate(deltaX / 2, deltaY / 2);

painter.drawImage(source, img);
Run Code Online (Sandbox Code Playgroud)

当然,在应用此方法之前,您应该检查源矩形是否小于目标矩形。为了简单起见,我省略了该代码,只是为了演示如何使图像居中。