效果图
实现原理
QPropertyAnimation和QGraphicsEffect的综合使用
核心代码
//旋转
m_vAnimation = new QVariantAnimation(this);
if (m_vAnimation) {
m_vAnimation->setDuration(2000);
m_vAnimation->setStartValue(0);
m_vAnimation->setEndValue(360);
m_vAnimation->setLoopCount(-1);
connect(m_vAnimation, &QVariantAnimation::valueChanged, this, &rotationLabel::sltMatrixChanged);
}
void rotationLabel::sltMatrixChanged(QVariant value)
{
// 不断修改旋转角度,并重绘
m_matrixNum = value.toInt();
update();
}
void rotationLabel::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
// 抗锯齿
painter.setRenderHints(QPainter::Antialiasing, true);
// 图片平滑处理
painter.setRenderHints(QPainter::SmoothPixmapTransform, true);
//加载图片资源
QPixmap disc(m_imagePath);
auto ateX = this->width() / 2;
auto ateY = this->height() / 2;
//设定旋转中心点
painter.translate(ateX, ateY);
//旋转的角度
painter.rotate(m_matrixNum);
//恢复中心点
painter.translate(-ateX, -ateY);
//画图操作
painter.drawPixmap(0, 0, this->width(), this->height(), disc);
}
//阴影
m_vShadowEffectAnimation = new QVariantAnimation(this);
if (m_vShadowEffectAnimation) {
m_vShadowEffectAnimation->setDuration(2000);
m_vShadowEffectAnimation->setKeyValueAt(0, 0);
m_vShadowEffectAnimation->setKeyValueAt(0.5, 100);
m_vShadowEffectAnimation->setKeyValueAt(1, 0);
m_vShadowEffectAnimation->setLoopCount(-1);
connect(m_vShadowEffectAnimation, &QVariantAnimation::valueChanged, this, &animationTest::sltShadowEffectRaduisChanged);
}
//设置边框阴影
m_shadowEffect = new QGraphicsDropShadowEffect(this);
if (m_shadowEffect) {
m_shadowEffect->setColor(QColor(0, 0, 139));
m_shadowEffect->setOffset(0, 0);
m_shadowEffect->setBlurRadius(0);
ui.label_shadowEffect->setGraphicsEffect(m_shadowEffect);
}
void animationTest::sltShadowEffectRaduisChanged(QVariant value)
{
auto radius = value.toInt();
if (m_shadowEffect) {
m_shadowEffect->setBlurRadius(radius);
}
}
//头像闪烁
m_opacityEffect = new QGraphicsOpacityEffect(this);
if (m_opacityEffect) {
ui.label_shadowEffect_2->setGraphicsEffect(m_opacityEffect);
m_opacityEffect->setOpacity(1);
}
m_vOpacityEffectAnimation = new QVariantAnimation(this);
if (m_vOpacityEffectAnimation) {
m_vOpacityEffectAnimation->setDuration(400);
m_vOpacityEffectAnimation->setKeyValueAt(0, 1.0);
m_vOpacityEffectAnimation->setKeyValueAt(0.5, 0.0);
m_vOpacityEffectAnimation->setKeyValueAt(1, 1.0);
m_vOpacityEffectAnimation->setLoopCount(-1);
connect(m_vOpacityEffectAnimation, &QVariantAnimation::valueChanged, this, [=](QVariant value) {
if (m_opacityEffect) {
m_opacityEffect->setOpacity(value.toDouble());
}
});
}