Creating Animated Lines on a Canvas in C#
In this article, we will explore how to create an animation of a line gradually drawn across a canvas in a C#/WPF project using code rather than XAML.
Implementation
The implementation involves using a Canvas within a ListBox to create the lines. Each line is represented by a LineViewModel that contains properties for coordinates, colors, thickness, and opacity.
A Timer is used to update the line coordinates over time, animating the line's movement across the canvas. The AnimationSpeed property controls the speed of the animation.
XAML Code
The XAML for the ListBox and its item template looks as follows:
<ListBox ItemsSource="{Binding}" x:Name="lst" Height="500" Width="500"> <ListBox.ItemsPanel> <ItemsPanelTemplate> <Canvas IsItemsHost="True"/> </ItemsPanelTemplate> </ListBox.ItemsPanel> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="FocusVisualStyle"> <Setter.Value> <Style TargetType="Control"> <Setter Property="Opacity" Value="0"/> </Style> </Setter.Value> </Setter> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListBoxItem"> <Line X1="{Binding X1}" Y1="{Binding Y1}" X2="{Binding X2}" Y2="{Binding Y2}" StrokeThickness="{Binding Thickness}" Opacity="{Binding Opacity}" x:Name="Line"> <Line.Stroke> <LinearGradientBrush StartPoint="0,0" EndPoint="1,1"> <GradientStop Color="{Binding Color1}" Offset="0"/> <GradientStop Color="{Binding Color2}" Offset="1"/> </LinearGradientBrush> </Line.Stroke> </Line> <ControlTemplate.Triggers> <Trigger Property="IsSelected" Value="true"> <Setter Property="Effect" TargetName="Line"> <Setter.Value> <DropShadowEffect Color="CornflowerBlue" ShadowDepth="3" BlurRadius="10"/> </Setter.Value> </Setter> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </ListBox.ItemContainerStyle> </ListBox>
ViewModel
The LineViewModel class is responsible for managing the properties and animation of each line:
public class LineViewModel : INotifyPropertyChanged { // ...properties and animation implementation... }
Usage
To use the animation, you can add LineViewModel objects to the DataContext of the ListBox. The Animate property can be used to start or stop the animation.
Conclusion
Using the techniques described above, you can create animated lines on a canvas in a C#/WPF project without resorting to XAML. The timer-based approach provides a simple and flexible way to control the animation's speed and behavior.
The above is the detailed content of How to Animate Line Drawing on a C# WPF Canvas Using Code?. For more information, please follow other related articles on the PHP Chinese website!