qt屏幕漫天雪花飘落_#include

全透明制作屏幕雪花效果

#include "pubbase.h"
#include "snownode.h"
#include <QSize>
#include <QPoint>
#include <QBitmap>
#include <QPixmap>
#include <QToolButton>
#include <QApplication>
#include <QDesktopWidget>
#include <QGraphicsScene>
#include <QGraphicsView>
const int SnowNode::MAXSWOW = 19;

SnowNode::SnowNode(QWidget *parent):
QToolButton(parent),m_animation(new QPropertyAnimation(this, "geometry"))
{
//必须设置为无边框,否则可见区域和图片绘制区域将出现不重叠
setWindowFlags( Qt::FramelessWindowHint );
resize(GetSnowSize());
//对图片进行缩放
m_pixmap.load(GetImgFileName());
m_pixmap = m_pixmap.scaled(this->size(),Qt::IgnoreAspectRatio);
setHidden(true);
m_areaSize.setWidth(QApplication::desktop()->width());
m_areaSize.setHeight(QApplication::desktop()->height());
}

//初始化雪花
void SnowNode::InitSnow()
{
this->move(qrand() % m_areaSize.width(), -32);
}

//设置雪花动画
void SnowNode::FallingAnimation()
{
int x = qrand()% m_areaSize.width();
//雪花飘落全程时间
m_animation->setDuration(8000);
m_animation->setStartValue(QRect( pos(), size()));
m_animation->setEndValue(QRect( QPoint(x,m_areaSize.height()), size()));
m_animation->start();
}

//返回雪花是否已着陆
bool SnowNode::IsLander()
{
if(this->pos().y() >= m_areaSize.height()
&& m_animation->state() == QAbstractAnimation::Stopped
)
{
return true;
}
return false;
}

void SnowNode::paintEvent(QPaintEvent *event)
{
//绘制背景图片
this->setIcon(QIcon(m_pixmap));
this->setIconSize(size());
//将png图片透明部分设置为穿透
this->setMask(m_pixmap.mask());
//绘制
QToolButton::paintEvent(event);

}

//每一朵雪花的大小,采用随机生成
QSize SnowNode::GetSnowSize()
{
int x = qrand() % 10;
return x >= 6 ? QSize(32,32) : x >= 3 ? QSize(24,24) : QSize(16,16);
}

//获取雪花文件名
QString SnowNode::GetImgFileName()
{
return QString().sprintf(":/image/_%d.png", qrand()% MAXSWOW);
}