WPF实现渐变淡入淡出的动画效果

时间:2022-01-30 08:08:39

1、实现原理

1.1 利用UIElement.OpacityMask属性,用于改变对象区域的不透明度的画笔。可以使元素的特定区域透明或部分透明,从而实现比较新颖的效果。

1.2 OpacityMask属性接受任何画刷,可利用LinearGradientBrush线性渐变画刷,通过对渐变画刷中各颜色点加以动画处理即可。

2、渐变淡入实现

渐变淡入效果,可通过事件触发器触发Loaded事件实现,所以可以仅用前端XAML语言实现。

2.1 设置对象的OpacityMask属性

<Grid.OpacityMask>
<LinearGradientBrush StartPoint="0.5,1" EndPoint="0.5,0">
<GradientStop Color="#00000000" Offset="0"/>
<GradientStop Color="#00000000" Offset="1"/>
<GradientStop Color="#00000000" Offset="1"/>
</LinearGradientBrush>
</Grid.OpacityMask>

2.2 设置对象的事件触发器

<Grid.Triggers>
<EventTrigger RoutedEvent="Loaded">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation From="1" To="0" Duration="0:0:1.5" Storyboard.TargetProperty="OpacityMask.(GradientBrush.GradientStops)[1].Offset"/>
<DoubleAnimation From="1" To="0" Duration="0:0:1" BeginTime="0:0:0.5" Storyboard.TargetProperty="OpacityMask.(GradientBrush.GradientStops)[2].Offset"/>
<ColorAnimation To="#FF000000" Duration="0" Storyboard.TargetProperty="OpacityMask.(GradientBrush.GradientStops)[2].Color"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Grid.Triggers>

3、渐变淡出实现

渐变淡出效果,由于事件触发器事件需要路由事件触发,所以需要使用后端代码实现。

3.1 准备渐变淡出的动画和画刷资源

<Window.Resources>
<Storyboard x:Key="ClosedStoryboard" Storyboard.TargetName="LoginGrid">
<DoubleAnimation From="1" To="0" Duration="0:0:2" Storyboard.TargetProperty="OpacityMask.(GradientBrush.GradientStops)[1].Offset"/>
<DoubleAnimation From="1" To="0" Duration="0:0:1.5" BeginTime="0:0:0.5"Storyboard.TargetProperty="OpacityMask.(GradientBrush.GradientStops)[2].Offset"/>
<ColorAnimation To="#00000000" Duration="0" Storyboard.TargetProperty="OpacityMask.(GradientBrush.GradientStops)[2].Color"/>
</Storyboard>
<LinearGradientBrush x:Key="ClosedBrush" StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Color="#FF000000" Offset="0"/>
<GradientStop Color="#FF000000" Offset="1"/>
<GradientStop Color="#FF000000" Offset="1"/>
</LinearGradientBrush>
</Window.Resources>

3.2 后端通过绑定按钮的Click事件实现

private void btnCancel_Click(object sender, RoutedEventArgs e)
{
this.IsEnabled = false; LoginGrid.OpacityMask = this.Resources["ClosedBrush"] as LinearGradientBrush;
Storyboard std = this.Resources["ClosedStoryboard"] as Storyboard;
std.Completed += delegate { this.Close(); }; std.Begin();
}

4、运行效果

4.1 效果图如下

WPF实现渐变淡入淡出的动画效果

欢迎转载,但请注明出处:http://www.cnblogs.com/julyweb/,谢谢!