我正在自定义窗口小部件中绘画以匹配“ Google样式”卡片。我的大多数尺寸和字体都正确,但是在绘制图像时始终会拉伸。这是参考图像和相关代码。我想将图像保持在默认的宽高比。

图片:

c++ - Qt-QPainter没有绘制带有纵横比的QPixmap-LMLPHP

    QRect topPortion = QRect(QPoint(0, 0), QSize(width(), (height()/4)*3));
    QPainterPath backgroundPath;
    backgroundPath.addRect(topPortion);
    QPainterPath bottom = getCornerPath().subtracted(backgroundPath);
    QRect bottomRect = QRegion(rect()).subtracted(QRegion(topPortion)).boundingRect();

    painter.fillPath(getCornerPath(), m_bColor);
    painter.fillPath(bottom, m_fColor);

    painter.drawPixmap(topPortion, m_image.scaled(topPortion.size(), Qt::KeepAspectRatio, Qt::FastTransformation));//Issue

    painter.setPen(QPen(QColor(50, 50, 50)));
    painter.setFont(titleFont);
    painter.drawText(QPointF(12, topPortion.height()+((bottomRect.height()-fontHeight)/2)+QFontMetrics(titleFont).ascent()), "Add Record");
    painter.setFont(subtitleText);
    painter.drawText(QPointF(12, topPortion.height()+((bottomRect.height()-fontHeight)/2)+fontHeight), "Add Record");

最佳答案

您正在使用m_image.scaled函数缩放图像,但是还会根据docs传递给painter.drawPixmap函数,topPortion变量:


  如果像素图和像素图都
  矩形大小不同。


所以我的解决方案是:

//Your's calculation area
QRect topPortion = QRect(QPoint(0, 0), QSize(width(), (height() / 4) * 3));

QPixmap pixmap = QPixmap(1024, 768); //Random image
pixmap.fill(Qt::red); //Random color

//Scaled size that will be used to set draw aera to QPainter, with aspect ratio preserved
QSize size = pixmap.size().scaled(topPortion.size(), Qt::KeepAspectRatio);

//Draw the pixmap inside the scaled area, with aspect ratio preserved
painter.drawPixmap(topPortion.x(), topPortion.y(), size.width(), size.height(), pixmap);

关于c++ - Qt-QPainter没有绘制带有纵横比的QPixmap,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47949448/

10-16 20:14