Qt背景图片填充、适应、拉伸、平铺、居中效果

您所在的位置:网站首页 html背景图拉伸平铺 Qt背景图片填充、适应、拉伸、平铺、居中效果

Qt背景图片填充、适应、拉伸、平铺、居中效果

2024-07-13 13:26| 来源: 网络整理| 查看: 265

背景图片在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



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3