【问题标题】:Kivy custom animation functionsKivy 自定义动画功能
【发布时间】:2018-08-08 18:43:02
【问题描述】:

有没有办法为动画组合各种内置函数,甚至创建自定义函数?

我喜欢in_out_cubicin_out_quadin_out_sine 函数,但我想做类似in_cubic_out_sine 的东西,看看是否可以。

尝试其他数学函数来创建各种效果也很有趣。

如何在 Kivy 中做到这一点?

【问题讨论】:

  • in_cubic_out_sine= 动画以三次函数开始,以正弦函数结束

标签: python animation kivy


【解决方案1】:

您指出的可能有多种解释,所以我将向您展示不同的可能性:

  • 使用从 p1 到 p2 的 in_cubic 动画和从 p2 到终点 p3 的 out_sine

    from kivy.animation import Animation
    from kivy.app import App
    from kivy.uix.button import Button
    
    class TestApp(App):
        def animate(self, instance):
            animation = Animation(pos=(200, 200), t='in_cubic')
            animation += Animation(pos=(400, 400), t='out_sine')
            animation.start(instance)
    
        def build(self):
            button = Button(size_hint=(None, None), text='plop',
                            on_press=self.animate)
            return button
    
    if __name__ == '__main__':
        TestApp().run()
    
  • 应用 50% 的提前 in_cubic 和另一个 out_sine,为此我们创建一个新函数:

    from kivy.animation import Animation, AnimationTransition
    from kivy.app import App
    from kivy.uix.button import Button
    
    
    def in_cubic_out_sine(progress):
        return AnimationTransition.in_cubic(progress) if progress < 0.5 else AnimationTransition.out_sine(progress)
    
    class TestApp(App):
        def animate(self, instance):
            animation = Animation(pos=(200, 200), t=in_cubic_out_sine)
            animation.start(instance)
    
        def build(self):
            button = Button(size_hint=(None, None), text='plop',
                            on_press=self.animate)
            return button
    
    if __name__ == '__main__':
        TestApp().run()
    

而且一般情况下你可以实现自己的函数,唯一要记住的是,进度取值从 0 到 1:

from kivy.animation import Animation
from kivy.app import App
from kivy.uix.button import Button

from math import cos, sin, pi, exp

def custom_animation(progress):
    return 1 - exp(-progress**2)*cos(progress*pi)**3

class TestApp(App):
    def animate(self, instance):
        animation = Animation(pos=(200, 200), t=custom_animation)
        animation.start(instance)

    def build(self):
        button = Button(size_hint=(None, None), text='plop',
                        on_press=self.animate)
        return button

if __name__ == '__main__':
    TestApp().run()

【讨论】:

  • 哇!几乎是我需要的!几乎,因为我需要像你的第一个例子一样的东西,但是 1) 第一个动画的参数 pos = (200, 200) 和第二个动画的参数 pos = (400, 400) (单向运动); 2)整个动画要流畅,动画中间不能有跳跃。我在第一个示例中看到了一个跳跃,在第二个示例中看到了一个非常大的跳跃,我正在 Ubuntu 上进行测试。你能在你的系统上检查一下吗?
  • 好的,但是跳跃的问题仍然存在。事实证明,如果我希望动画流畅,我不能使用第一个或第二个示例。我使用匀速运动检查了它(没有 "t=..." ) - 即使在这种情况下,我也看到动画之间的跳转
  • 我在@eyllanesc 的第一个示例中使用了动画,但没有看到“跳跃”。我已经看到当两个动画不匹配时可能出现的“跳跃”。在Animation 文档中的转换函数图中,线的斜率表示速度。如果第一个动画的结束速度与第二个动画的开始速度不匹配,您可以看到可能被描述为“跳跃”的情况。
猜你喜欢
  • 2013-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-14
  • 1970-01-01
  • 1970-01-01
  • 2015-01-09
  • 2011-11-06
相关资源
最近更新 更多