背景圖片在windows設置裏有填充(按寬高都填滿窗口,多餘部分溢出隱藏)、適應(寬高適應窗口,缺少的部分用背景色填充)、拉伸(將圖片寬高拉伸至窗口寬高,可能變形)、平鋪(左上角繪製圖形,一直到繪製滿窗口爲止)、居中(將圖片繪製到窗口正中,如果圖片比窗口小,用背景色填充)。
在Qt裏,我今天在查找到一篇文章後,得以實現,後來進行了改進,都用QImage做到了,這樣就與文件的磁盤路徑脫鉤,可以做到將圖片保存到二進制文件裏了。、
代碼如下所示,相信用過Qt的人一定能適配到自己代碼裏。
QLabel *label = ui->labelBgImg;
label->setStyleSheet("background-color:white;");
label->setPixmap(QPixmap());
if (bgImage.isNull()) {
return;
}
if (bgImage.width() > label->width() ||
bgImage.height() > label->height()) {
// 爲了更好的演示各種效果
bgImage = bgImage.scaled(label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
}
if (fillTypeText == "填充") {
QPixmap pixmap;
pixmap.convertFromImage(bgImage);
label->setAlignment(Qt::AlignCenter);
label->setPixmap(pixmap.scaled(label->size(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation));
} else if (fillTypeText == "適應") {
label->setAlignment(Qt::AlignCenter);
QPixmap pixmap;
pixmap.convertFromImage(bgImage);
label->setPixmap(pixmap.scaled(label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
} else if (fillTypeText == "拉伸") {
QPixmap pixmap;
pixmap.convertFromImage(bgImage);
label->setPixmap(pixmap.scaled(label->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
} else if (fillTypeText == "平鋪") {
QPixmap pixmap(label->size());
QPainter painter(&pixmap);
int drawedWidth = 0;
int drawedHeight = 0;
while (1) {
drawedWidth = 0;
while (1) {
painter.drawImage(drawedWidth, drawedHeight, bgImage);
drawedWidth += bgImage.width();
if (drawedWidth >= pixmap.width()) {
break;
}
}
drawedHeight += bgImage.height();
if (drawedHeight >= pixmap.height()) {
break;
}
}
label->setPixmap(pixmap);
} else if (fillTypeText == "居中") {
QPixmap pixmap(label->size());
pixmap.fill(Qt::white); // 一定要填充白色,否則會有無效圖形
QPainter painter(&pixmap);
int x = (label->size().width() - bgImage.width()) / 2;
int y = (label->size().height() - bgImage.height()) / 2;
painter.drawImage(x, y, bgImage);
label->setPixmap(pixmap);
}
查閱資料:https://blog.csdn.net/bochen_cwx/article/details/82083570