故事板动画滞后

时间:2017-10-03 12:40:58

标签: c# animation storyboard windows-phone-8.1 windows-phone-silverlight

我创建了一个降雪动画,但它有点滞后,如果我在空白的新应用程序中创建这个动画它工作正常但如果尝试构建更多的东西并使用它完全构建应用程序它开始滞后。

XAML

<Grid>
    <Canvas x:Name="ContentPanel" Height="768">

    </Canvas>
</Grid>

C#

using System.Windows.Shapes;
using System.Windows.Media.Animation;
using System.Windows.Media;


public partial class MainPage : PhoneApplicationPage
{
    private static Random random;

    public MainPage()
    {
        InitializeComponent();
        random = new Random();
        this.StartFallingSnowAnimation();
    }

    private Ellipse GenerateEllipse()
    {
        Ellipse element = new Ellipse();
        element.Fill = new SolidColorBrush(Colors.Cyan);
        element.Height = 8.0;
        element.Width = 8.0;
        this.ContentPanel.Children.Add(element);
        return element;
    }

    private Storyboard CreateStoryboard(UIElement element, double to, double toLeft)
    {
        Storyboard result = new Storyboard();
        DoubleAnimation animation = new DoubleAnimation();
        animation.To = to;
        Storyboard.SetTargetProperty(animation, new PropertyPath("(Canvas.Top)"));
        Storyboard.SetTarget(animation, element);

        DoubleAnimation animationLeft = new DoubleAnimation();
        animationLeft.To = toLeft;
        Storyboard.SetTargetProperty(animationLeft, new PropertyPath("(Canvas.Left)"));
        Storyboard.SetTarget(animationLeft, element);

        result.Children.Add(animation);
        result.Children.Add(animationLeft);

        return result;
    }

    private void StartFallingSnowAnimation()
    {
        for (int i = 0; i < 20; i++)
        {
            Ellipse localCopy = this.GenerateEllipse();
            localCopy.SetValue(Canvas.LeftProperty, i * 30 + 1.0);

            double y = Canvas.GetTop(localCopy);
            double x = Canvas.GetLeft(localCopy);

            double speed = 5 * random.NextDouble();
            double index = 0;
            double radius = 30 * speed * random.NextDouble();

            localCopy.Opacity = .3 + random.NextDouble();

            CompositionTarget.Rendering += delegate (object o, EventArgs arg)
            {
                index += Math.PI / (180 * speed);

                if (y < this.ContentPanel.DesiredSize.Height)
                {
                    y += .3 + speed;
                }
                else
                {
                    y = -localCopy.Height;
                }

                Canvas.SetTop(localCopy, y);
                Canvas.SetLeft(localCopy, x + radius * Math.Cos(index));
                Storyboard animation = this.CreateStoryboard(localCopy, y, x + radius * Math.Cos(index));
                Storyboard.SetTarget(animation, localCopy);
                animation.Begin();

            };
        }
    }
}

它在一个空的应用程序中完美运行,但如果在app build中使用更多控件或完全构建应用程序,则开始滞后。

0 个答案:

没有答案