使用渐变的方式浏览图片,效果如下:
制作的大概思路为使用Qt的属性动画,改变画笔绘制时的透明度,先绘制上一张图片,再绘制要显示的图片。
下面仅贴出本示例的关键代码:
头文件
#include <QPropertyAnimation>
class ImageView : public QWidget
{
Q_OBJECT
Q_PROPERTY(float alpha READ alpha WRITE setAlpha)
public:
ImageView();
~ImageView();
private:
float m_PainterAlpha;
float alpha(void);
void setAlpha(float alpha);
// 背景图片
QPixmap m_BackgroundPixmap;
// 动画
QPropertyAnimation *m_PropertyAnimation = nullptr;
// 当前要显示的图片
QPixmap m_CurrentPixmap;
QWidget *m_ButtonWidget = nullptr;
QLabel *m_PageTagLabel = nullptr;
QPushButton *m_PreviousButton = nullptr;
QPushButton *m_NextButton = nullptr;
}
源文件
#include "BezierCurve.h"
#include <QPainter>
#include <QVBoxLayout>
#include <QColor>
#include <QApplication>
#include <QStyleOption>
BezierCurve::BezierCurve(QWidget *parent)
:QWidget(parent)
{
m_SampleCount = 100;
m_StartColor = QColor(255, 255, 0);
m_EndColor = QColor(0, 255, 255);
this->setProperty("NormalWidget", "NormalWidget");
}
BezierCurve::~BezierCurve()
{
}
void BezierCurve::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
// 绘制样式
QStyleOption opt;
opt.init(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &painter, this);
painter.setRenderHint(QPainter::Antialiasing, true);
// 绘制贝塞尔曲线
drawBezierCurve(&painter, QPointF(20, 20), QPointF(20, 500), QPointF(500, 20), QPointF(500, 500));
return QWidget::paintEvent(event);
}
void BezierCurve::drawBezierCurve(QPainter* painter, QPointF startPos, QPointF c1, QPointF c2, QPointF endPos)
{
painter->save();
QPointF tempPos = startPos;
for (int i=0; i<=m_SampleCount; ++i)
{
// 设置画笔
QPen pen;
QColor lineColor = getGradientColor(i);
pen.setColor(lineColor);
pen.setWidth(3);
painter->setPen(pen);
qreal t = i * 1.0 / m_SampleCount;
QPointF pos = pow((1 - t), 3) * startPos + \
3 * t * pow((1 - t), 2) * c1 + \
3 * t * t * (1 - t) * c2 + \
pow(t, 3) * endPos;
// 绘制贝塞尔曲线
painter->drawLine(tempPos, pos);
tempPos = pos;
}
painter->restore();
}
QColor BezierCurve::getGradientColor(int index)
{
qreal redInterval = (m_EndColor.red() - m_StartColor.red()) * 1.0 / m_SampleCount;
qreal greenInterval = (m_EndColor.green() - m_StartColor.green()) * 1.0 / m_SampleCount;
qreal blueInterval = (m_EndColor.blue() - m_StartColor.blue()) * 1.0 / m_SampleCount;
QColor gradientColor;
gradientColor.setRed(redInterval * index + m_StartColor.red());
gradientColor.setGreen(greenInterval * index + m_StartColor.green());
gradientColor.setBlue(blueInterval * index + m_StartColor.blue());
return gradientColor;
}