QPainter DrawImage CenterAligned

时间:2013-09-23 12:19:20

标签: qt qpainter

有没有办法在QPainter居中对齐上绘制图像?我看到QPainter::drawText为我们提供了此条款,但drawImage没有。我有一个源矩形,目标矩形和图像。当源大小较小时,图像将在页面左侧绘制。我希望它是印刷中心对齐的。

3 个答案:

答案 0 :(得分:2)

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

应绘制的样本图像

// 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);

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

答案 1 :(得分:2)

画家没有大小,但是它上面的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);

答案 2 :(得分:1)

我想展示一个更完整的示例,其中可变图像大小保持在提供的区域范围内,以添加到其他好的答案中。

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);
}