#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
protected:
void paintEvent(QPaintEvent *event)override;
private:
enum class AspectRatioMode
{
zoomWithWindow = 0,//随窗口缩放
keepAspectRatio,//保持原图
scaleAspectFit, //保持纵横比并缩放
scaleAspectFill //保持纵横比并填充
};
AspectRatioMode mode{AspectRatioMode::scaleAspectFill};
void drewBg(QPainter * painter,const QRect & rect,const QPixmap & pixmap);
QPixmap bgImage;
};
#endif // WIDGET_H
#include "widget.h"
#include <QPainter>
#include <QPaintEvent>
#include <QDebug>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
bgImage.load(":/backgroundImage1.jpg");
}
Widget::~Widget()
{
}
void Widget::drewBg(QPainter * painter,const QRect & rect,const QPixmap & pixmap)
{
if(mode == AspectRatioMode::zoomWithWindow)
{
painter->drawPixmap(rect,pixmap);
}
else if(mode == AspectRatioMode::keepAspectRatio)
{
painter->drawPixmap(rect.topLeft(),pixmap);
}
else if(mode == AspectRatioMode::scaleAspectFit)
{
auto tempPximap = pixmap.scaled(rect.size(),Qt::KeepAspectRatio);
if(rect.width() == tempPximap.width())
{
painter->drawPixmap(QPoint(0,(rect.height() - tempPximap.height()) / 2),tempPximap);
}
else
{
painter->drawPixmap(QPoint((rect.width() - tempPximap.width())/2,0),tempPximap);
}
}
else if(mode == AspectRatioMode::scaleAspectFill)
{
if(rect.width() > rect.height())
{
auto y2 = pixmap.height() * rect.width() / pixmap.width();
QPixmap tempPximap = pixmap.scaled(rect.width(),y2,Qt::KeepAspectRatio);
painter->drawPixmap(rect,tempPximap.copy(0,(y2 - rect.height()) / 2,rect.width(),rect.height()));
}
else
{
auto x2 = pixmap.width() * rect.height() / pixmap.height();
QPixmap tempPximap = pixmap.scaled(x2,rect.height(),Qt::KeepAspectRatio);
painter->drawPixmap(rect,tempPximap.copy((x2 - rect.width()) / 2,0,rect.width(),rect.height()));
}
}
}
void Widget::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing,true); //反走样开启
const auto rect = event->rect();
painter.fillRect(rect,Qt::cyan);
drewBg(&painter,rect,bgImage);
}
1、随窗口缩放
2、 保持原图
3、保持纵横比并缩放
4、保持纵横比并填充
示意图:
效果图: