Animate Percentage Values

Currently you can only animate elements with pixel values. This is understandable as the animation API is experimental, but hopefully soon you will be able to set values in animations with an attributed LengthUnit. I might not always know the width or height of an element in pixels, but I do know that I want it to go to from 0 to 100%.

public static ValueAnimation<StyleValues> AnimateHeight(this VisualElement target, float startHeight, float endHeight, int durationMs, Action callback = null, Func<float, float> easing = null)
    {
        if (easing == null) easing = EaseInOutQuint;
        return target.experimental.animation .Start(new StyleValues { height = startHeight }, new StyleValues { height = endHeight }, durationMs).Ease(easing).OnCompleted(callback);
    }

You can get the width/height of an element in pixels by calling element.resolvedStyle.width (or height) and then do the pixel animation.

1 Like

Good idea! Although I still think the percentage option should be there. Some of my elements needs to expand to fit all of their children. These elements can change width and height outside of animations and can therefore not have set pixel values. At the moment I should be able to do some callbacks when the animations are complete and make the height or width percentage values again, but still, having it built in would save me from this trickery.

You could ease directly on the percent value and apply the value to the inline style manually.

 public static ValueAnimation<float> AnimatePercentHeight(this VisualElement target, float startPercent, float endPercent, int durationMs, Action callback = null, Func<float, float> easing = null)
        {
            if (easing == null) easing = EaseInOutQuint;
            return target.experimental.animation .Start(startPercent, endPercent, durationMs, (e, percentHeight) =>
                {
                    e.style.height = Length.Percent(percentHeight);
                }).Ease(easing).OnCompleted(callback);
        }

Supporting transitions straight from uss will make these things way easier in the future

2 Likes

Great example! I will use this to further develop my animation API.