首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >QPainter DrawImage CenterAligned

QPainter DrawImage CenterAligned
EN

Stack Overflow用户
提问于 2013-09-23 20:19:20
回答 3查看 7.7K关注 0票数 5

有没有办法在QPainter上画一张居中对齐的图片?我看到QPainter::drawText给了我们这个条款,但是drawImage没有。我有一个源rect,目标rect和一个图像。当源大小较小时,图像将绘制在页面的左侧。我想把它打印出来居中对齐。

EN

回答 3

Stack Overflow用户

发布于 2013-09-23 21:19:44

画笔没有尺寸,但它所画的device()有尺寸。您可以使用QRect(painter.device()->width(), painter.device()->height())作为要在其中居中显示图像的矩形。

然后将图像居中绘制,如下所示:

代码语言:javascript
复制
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);
票数 8
EN

Stack Overflow用户

发布于 2013-09-23 20:36:54

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

应绘制的示例图像

代码语言:javascript
复制
// The image to draw - blue rectangle 100x100.
QImage img(100, 100, QImage::Format_ARGB32);
img.fill(Qt::blue);

在paint事件处理程序中

代码语言:javascript
复制
[..]
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);

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

票数 2
EN

Stack Overflow用户

发布于 2015-01-26 17:18:07

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

代码语言:javascript
复制
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);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18959083

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档