Search code examples
pythonanimationkivyfont-sizetext-size

How to animate font size without text reordering, when `text_size=self.size`


I need to display some text and later on animate its font size. The text must not exceed the size of its widget so I use text_size: self.size (I don't mind the text exceeding its widget size during animation though)

enter image description here

The problem is that animation of the font size forces the text to reorder, which is ugly (red circle in image got there during animation)

enter image description here

I would prefer it did exceed temporarily that size, instead.

How can I achieve both the text not exceeding its widget's size, and during font-size animation to exceed that size (shown in image below)?

enter image description here


Code used:

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


kv = """
<MyWidget>:
    text: 'long text...' * 5
    text_size: self.size
    halign: 'center'
    valign: 'middle'
    on_release: self.animate_function()
"""


Builder.load_string(kv)


class MyWidget(Button):

    def animate_function(self):
        initial_font_size = self.font_size
        anim = Animation(font_size=initial_font_size * 1.5, duration=2)
        anim += Animation(font_size=initial_font_size, duration=2)
        anim.start(self)


class MyButtonsApp(App):
    def build(self):
        return MyWidget()


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

Solution

  • You could animate a stretching of the text instead of its font size. This would be slightly less graphically precise (like enlarging a small image looks blurry), but might be good enough depending on your parameters. It would also be much more performant; animating the font size requires re-rendering the texture each time.

    I have a very simple example of using a Scale instruction for this, which you can find here.