【发布时间】:2019-04-15 19:22:17
【问题描述】:
我正在尝试为 GradientBrush 创建动画,该动画将为每个渐变设置动画,以无限期地循环遍历渐变中包含的所有颜色。
由于这项任务的复杂性,我已经开始在后面的代码中处理所有内容,而不是在 XAML 中。
幸运的是,我的代码没有出现错误或异常。
不幸的是,它也完全没有做任何事情。
符合minimal, complete and verifiable example 要求:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
namespace MCVE {
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class Program {
private static LinearGradientBrush TestBrush { get; } =
new LinearGradientBrush(
new GradientStopCollection( new[ ]{
new GradientStop( Colors.Black, 0 / 1.0D ),
new GradientStop( Colors.White, 1 / 1.0D )
} ), new Point( 0.0D, 0.0D ), new Point( 1.0D, 1.0D ) );
[STAThread]
public static int Main( ) {
Storyboard board = CreateStoryboard( TestBrush );
Window w = new Window( ){
Background = TestBrush
};
w.Loaded += new RoutedEventHandler(
( S, E ) => board.Begin( w, true ) );
Program program = new Program( );
program.InitializeComponent( );
return program.Run( w );
}
public static Storyboard CreateStoryboard( GradientBrush brush ) {
Storyboard board = new Storyboard( ){
Duration = new Duration( TimeSpan.FromSeconds( 1.0D ) ),
RepeatBehavior = RepeatBehavior.Forever
};
foreach (
var animation
in brush.GradientStops.Select(
GS => _CreateGradientStopAnimation(
GS, brush.GradientStops.SkipWhile( G => G != GS
).Concat( brush.GradientStops.TakeWhile( G => G != GS )
).Concat( new[ ] { GS } ).Select( G => G.Color ) ) ) )
board.Children.Add( animation );
return board;
ColorAnimationUsingKeyFrames _CreateGradientStopAnimation(
GradientStop stop, IEnumerable<Color> colors ) {
ColorAnimationUsingKeyFrames animation =
new ColorAnimationUsingKeyFrames( );
Storyboard.SetTarget( animation, stop );
Storyboard.SetTargetProperty(
animation, new PropertyPath(
GradientStop.ColorProperty ) );
foreach ( var keyFrame in colors.Select(
C => new EasingColorKeyFrame( C ) ) )
animation.KeyFrames.Add( keyFrame );
return animation;
}
}
}
}
我已经尝试为画笔中的每个渐变只使用ColorAnimationUsingKeyFrames,并且确实有效,但我更喜欢使用Storyboard(如果可能的话),以便可以一起启动所有动画。
我正在尝试做的事情可能吗?如果是这样,我做错了什么?
如果没有,我可以做些什么来完成我想要在这里完成的事情(同时启动许多不同的动画)?
【问题讨论】:
-
一目了然,动画不是连板都没有返回吗?就我个人而言,我非常喜欢 xaml 来处理这类事情......
-
@ChrisW。 Board 在声明本地函数
_CreateGradientStopAnimation(...之前返回。我很想使用 XAML,但要求太复杂,我无法在 XAML 中实现,主要是因为我不知道如何使它在 XAML 中工作。
标签: c# wpf xaml storyboard code-behind