PySide6 如此丝滑的开场动画
动画预览:
原理剖析:
通过自定义属性“角度”,配置属性动画保证持续更新绘制,并重写绘制事件
上强度:
1.自定义动画
from PySide6.QtCore import Qt,QPropertyAnimation,QEasingCurve,Property,Signal
class LogoImg(QLabel):
def __init__(self,parent=None):
super().__init__(parent)
self.angle = 0
@Property(int) # 注意这里是PySide6封装的装饰器
def angle(self):
return self._angle
@angle.setter
def angle(self,value):
self._angle = value # 注意这里声明的是一个内部变量,通过这个内部变量去访问修改angle
self.update() # 更新绘制(调用PainterEvent)
2.重写绘制事件
def paintEvent(self, event):
painter = QPainter(self)
pixmap = QPixmap('./img/terminal-solid-156.png')
x,y = (self.geometry().size()-pixmap.size()).toTuple()
painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform) # 设置渲染提示以达到不失真
painter.translate(self._width/2,self._height/2) # 平移到旋转中心
painter.rotate(self.angle) # 旋转
painter.translate(-self._width/2,-self._height/2) # 平移回原位置
painter.drawPixmap(x/2,y/2,pixmap)
3.配置属性动画
self.imgAmimation = QPropertyAnimation(self,b'angle')
self.imgAmimation.setDuration(960) # 设置动画的持续时间,以毫秒为单位 1秒 = 1000毫秒
self.imgAmimation.setStartValue(0)
self.imgAmimation.setEndValue(360)
self.imgAmimation.setEasingCurve(QEasingCurve.Type.InOutBack) # 设置执行时间曲线(可以简单理解为执行的不同效果)
self.imgAmimation.setLoopCount(-1) # 重复次数(-1为无数次)