有没有办法在QPainter上画一张居中对齐的图片?我看到QPainter::drawText给了我们这个条款,但是drawImage没有。我有一个源rect,目标rect和一个图像。当源大小较小时,图像将绘制在页面的左侧。我想把它打印出来居中对齐。
发布于 2013-09-23 21:19:44
画笔没有尺寸,但它所画的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);发布于 2013-09-23 20:36:54
我将尝试执行以下操作(请遵循源代码注释):
应绘制的示例图像
// The image to draw - blue rectangle 100x100.
QImage img(100, 100, QImage::Format_ARGB32);
img.fill(Qt::blue);在paint事件处理程序中
[..]
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);当然,在应用此方法之前,您应该检查源矩形是否小于目标矩形。为了简单起见,我省略了这些代码,只是为了演示如何将图像居中。
发布于 2015-01-26 17:18:07
我想要展示一个更完整的示例,它具有可变的图像大小,并保持在所提供的区域范围内,以添加到其他很好的答案中。
void ImageView::paintEvent(QPaintEvent*)
{
if (this->imageBuffer.empty()){ return; }
double widgetWidth = this->width();
double widgetHeight = this->height();
QRectF target(0, 0, widgetWidth, widgetHeight);
QImage tempQImage = *this->imageBuffer.at(this->imageBuffer.count()-1);
tempQImage = tempQImage.scaled(rect().size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
double imageSizeWidth = static_cast<double>(tempQImage.width());
double imageSizeHeight = static_cast<double>(tempQImage.height());
QRectF source(0.0, 0.0, imageSizeWidth, imageSizeHeight);
int deltaX = 0;
int deltaY = 0;
if(source.width() < target.width())
deltaX = target.width() - source.width();
else
deltaX = source.width() - target.width();
if(source.height() < target.height())
deltaY = target.height() - source.height();
else
deltaY = source.height() - target.height();
QPainter painter(this);
painter.translate(deltaX / 2, deltaY / 2);
painter.drawImage(source, tempQImage);
}https://stackoverflow.com/questions/18959083
复制相似问题