5

有没有办法在QPainter中心对齐上绘制图像?我看到QPainter::drawText给了我们这个规定,但drawImage没有。我有一个源矩形、目标矩形和一个图像。当源大小较小时,图像将绘制在页面的左侧。我希望它打印中心对齐。

4

3 回答 3

8

画家没有尺寸,但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-23T13:19:44.400 回答
2

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

应绘制的示例图像

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

在绘制事件处理程序中

[..]
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);

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

于 2013-09-23T12:36:54.230 回答
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);
}
于 2015-01-26T09:18:07.320 回答