一、使用QLabel显示图片
使用scaled()函数缩放图片
QImage QImage::scaled(const QSize &size, Qt::AspectRatioMode aspectRatioMode = Qt::IgnoreAspectRatio, Qt::TransformationMode transformMode = Qt::FastTransformation) const
- size表示给定缩放后的尺寸。
- AspectRatioMode 选择缩放的模式,如果是IgnoreAspectRatio模式(缺省)即按照给定的尺寸显示;
KeepAspectRatio,则按照给定的尺寸将图像缩放为内部大小尽可能大的矩形,从而保留纵横比。
KeepAspectRatioByExpanding,则图像将缩放为一个外部尺寸尽可能小的矩形,从而保持纵横比。
我们这里选择KeepAspectRatio模式即可。 - TransformationMode 模式,是否让图像看起来更平滑。
Qt::FastTransformation(缺省),执行的更快,没有平滑。
Qt::SmoothTransformation,使得图像更平滑。
这里选择Qt::SmoothTransformation。
MyDrawImage::MyDrawImage(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
QImage img("./1.jpeg");
int WindowW = this->width();
int WindowH = this->height();
ui.label->setGeometry(0, 0, WindowW, WindowH);
QImage scalimg = img.scaled(ui.label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
ui.label->setPixmap(QPixmap::fromImage(scalimg));
}
运行结果:
上图第一张:是根据窗口显示效果
上图第二张:鼠标放大了窗口显示效果(很明显,在窗口放大,图片没有跟随窗口变化)
二、使用QPainter绘制图片,并使其图片跟随窗口变化
void MyDrawImage::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPainter painter(this);
//获取当前窗口与图片的比值
float fRatioX = this->width()*1.0 / m_Image.width();
float fRatioY = this->height()*1.0 / m_Image.height();
float fRatioRes = qMin(fRatioX, fRatioY);
//计算新的Rect
int width = m_Image.width() * fRatioRes;
int height = m_Image.height() * fRatioRes;
int startX = (this->width() - width) / 2;
int startY = (this->height() - height) / 2;
// 绘制图像
QRect picRect(startX, startY, width, height);
painter.drawImage(picRect, m_Image);
}