Qt - QPainter没有绘制QPixmap w /纵横比

问题描述 投票:0回答:1

我在自定义小部件中绘画以匹配“Google-Styled”卡片。我有大多数尺寸和字体正确但是在绘制图像时它总是被拉伸。这是参考图像和相关代码。我想保持图像的默认宽高比。

图片:

enter image description here

    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");
c++ qt qpainter
1个回答
2
投票

你用m_image.scaled函数缩放你的图像,但是也传递给painter.drawPixmap函数,topPortion变量,并根据docs

如果像素图和矩形大小都不一致,则缩放像素图以适合矩形。

所以我的解决方案是:

//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);
© www.soinside.com 2019 - 2024. All rights reserved.