Animate line ads in wpf?

Is there a way to animate adorner's opacity property so that the line appears from a slight reddish color to a full red color>

I have the following code in the OnRender () method:

Pen renderPen = new Pen(new SolidColorBrush(Colors.Red), 2.5); drawingContext.DrawLine(renderPen, adornedElementRect.Value.TopLeft, adornedElementRect.Value.BottomLeft); 

thanks

+4
source share
1 answer

Here is an example; press the button and the red line will fade.

XAML for window:

 <Window x:Class="AnimAdornerTest.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <Button Width="100" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Click="Button_Click">Show Adorner</Button> <Rectangle x:Name="toBeAdorned" Fill="#E8E8E8" Width="100" Height="100"></Rectangle> </Grid> </Window> 

Code for the window:

 using System.Windows; using System.Windows.Documents; namespace AnimAdornerTest { public partial class MainWindow : Window { private AdornerLayer _adornerLayer; private AnimAdorner _adorner; public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { if (_adornerLayer == null) { _adornerLayer = AdornerLayer.GetAdornerLayer(toBeAdorned); } if (_adorner != null) { _adornerLayer.Remove(_adorner); } _adorner = new AnimAdorner(toBeAdorned); _adornerLayer.Add(_adorner); } } } 

Adorner:

 using System; using System.Windows; using System.Windows.Documents; using System.Windows.Media; using System.Windows.Media.Animation; namespace AnimAdornerTest { public class AnimAdorner : Adorner { public AnimAdorner(UIElement adornedElement) : base(adornedElement) { Loaded += AnimAdorner_Loaded; } void AnimAdorner_Loaded(object sender, RoutedEventArgs e) { DoubleAnimation myDoubleAnimation = new DoubleAnimation { From = 1.0, To = 0.0, Duration = new Duration(TimeSpan.FromSeconds(1)), AutoReverse = true, RepeatBehavior = RepeatBehavior.Forever }; Storyboard myStoryboard = new Storyboard(); myStoryboard.Children.Add(myDoubleAnimation); Storyboard.SetTarget(myStoryboard, this); Storyboard.SetTargetProperty(myDoubleAnimation, new PropertyPath(OpacityProperty)); myStoryboard.Begin(this); } protected override void OnRender(DrawingContext drawingContext) { Pen renderPen = new Pen(new SolidColorBrush(Colors.Red), 2.5); drawingContext.DrawLine(renderPen, new Point(0, 0), new Point(AdornedElement.RenderSize.Width, AdornedElement.RenderSize.Height)); } } } 
+5
source

Source: https://habr.com/ru/post/1416495/


All Articles