簡體   English   中英

Qt-QPainter沒有繪制帶有縱橫比的QPixmap

[英]Qt - QPainter not painting QPixmap w/ Aspect Ratio

我正在自定義窗口小部件中繪畫以匹配“ Google樣式”卡片。 我的大多數尺寸和字體都正確,但是在繪制圖像時始終會拉伸。 這是參考圖像和相關代碼。 我想將圖像保持在默認的寬高比。

圖片:

在此處輸入圖片說明

    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函數縮放圖像,但是還會傳遞給painter.drawPixmap函數, topPortion變量並根據docs進行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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM