繁体   English   中英

将C#动画代码转换为情节提要

[英]Convert C# animation code to storyboard

我有以下可行的方法。 我想将其放在返回Storyboard的实用程序方法中。 我将其转换为情节提要的所有尝试均以失败告终,并且我花费了大量时间进行研究。 我准备放弃,除非有人来救我。

这是我要转换的代码:

public override void Begin(FrameworkElement element, int duration)
{
    var transform = new ScaleTransform();
    element.LayoutTransform = transform;

    var animation = new DoubleAnimation
                        {
                            From = 1,
                            To = 0,
                            Duration = TimeSpan.FromMilliseconds(duration),
                            FillBehavior = FillBehavior.Stop,
                            EasingFunction = new QuinticEase { EasingMode = EasingMode.EaseIn }
                        };

    transform.BeginAnimation(ScaleTransform.ScaleXProperty, animation);
    transform.BeginAnimation(ScaleTransform.ScaleYProperty, animation);
}

因此,我想返回一个Storyboard,而不是两个BeginAnimation()调用,所以我要做的就是调用Storyboard.Begin()。 我知道这样做并不难,但我只是不明白。

谢谢。

编辑:为响应HB的建议,我尝试了下面的代码,仍然无法正常工作:

private static Storyboard CreateAnimationStoryboard(FrameworkElement element, int duration)
{
    var sb = new Storyboard();
    var scale = new ScaleTransform(1, 1);
    element.RenderTransform = scale;
    element.RegisterName("scale", scale);

    var animation = new DoubleAnimation
    {
        From = 1,
        To = 0,
        Duration = TimeSpan.FromMilliseconds(duration),
        FillBehavior = FillBehavior.Stop,
        EasingFunction = new QuinticEase { EasingMode = EasingMode.EaseIn }
    };
    sb.Children.Add(animation);

    Storyboard.SetTarget(animation, scale);
    Storyboard.SetTargetProperty(animation, new PropertyPath(ScaleTransform.ScaleXProperty));

    return sb;
}

我知道我只对X轴进行了动画处理-只想先做点工作。

您将需要两个动画,然后使用SetTargetPropertySetTargetName将附加的Storyboard属性设置为对正确对象上的正确属性进行动画SetTargetName

由于情节提要板的工作方式,您还需要设置一个名称范围( NameScope.SetNameScope ),注册转换的名称,并使用包含元素重载调用StoryBoard.Begin

例如

NameScope.SetNameScope(element, new NameScope());

var transform = new ScaleTransform();
var transformName = "transform";
element.RegisterName(transformName, transform);
element.RenderTransform = transform;

var xAnimation = new DoubleAnimation(2, TimeSpan.FromSeconds(1));
var yAnimation = xAnimation.Clone();

var storyboard = new Storyboard()
{
    Children = { xAnimation, yAnimation }
};

Storyboard.SetTargetProperty(xAnimation, new PropertyPath("(ScaleTransform.ScaleX)"));
Storyboard.SetTargetProperty(yAnimation, new PropertyPath("(ScaleTransform.ScaleY)"));

Storyboard.SetTargetName(xAnimation, transformName);
Storyboard.SetTargetName(yAnimation, transformName);

storyboard.Begin(element);

我建议使用Expression Blend并从那里开始录制,它应该在XAML中创建情节提要。 与其使用C#对其进行硬编码,然后尝试将其一一转换为情节提要,这可能是一个容易发生的错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM