
用C# 在畫布上建立動畫線條
在本文中,我們將探索如何建立逐漸繪製的線條動畫使用程式碼而不是C#/WPF 專案中的畫布XAML。
實作
實作涉及在 ListBox 中使用 Canvas 來建立線條。每條線都由 LineViewModel 表示,其中包含座標、顏色、粗細和不透明度等屬性。
計時器用於隨時間更新線座標,從而為線在畫布上的移動設定動畫。 AnimationSpeed 屬性控制動畫的速度。
XAML 代碼
ListBox 及其項目模板的XAML 如下所示:
<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
LineViewModel類別負責管理每行的屬性和動畫:
public class LineViewModel : INotifyPropertyChanged
{
// ...properties and animation implementation...
}用法
要使用動畫,可以將 LineViewModel 物件加入 ListBox 的 DataContext 中。 Animate 屬性可用於啟動或停止動畫。
結論
使用上述技術,您可以在 C#/ 畫布上建立動畫線條WPF 專案無需使用 XAML。基於計時器的方法提供了一種簡單且靈活的方法來控制動畫的速度和行為。
以上是如何使用程式碼在 C# WPF 畫布上繪製線條動畫?的詳細內容。更多資訊請關注PHP中文網其他相關文章!