[英]How to draw and animate multiple RectangleGeometry.Rect in WPF/C#
以下代碼有效地創建了一個矩形並為其設置了動畫。 我想做的是創建和設置多個矩形的動畫。
將qtyX
和qtyY
更改為多個后,我立即收到錯誤qtyY
。
知道如何解決這個問題嗎?
無法在此范圍內注冊重復名稱“ MyAnimatedRectangleGeometry”。
XAML:
<Canvas Name="MyCanvas" Background="#FFFFF5F5"/>
代碼隱藏:
private void button_Click(object sender, RoutedEventArgs e)
{
double length = 100;
double height = 50;
int qtyX = 1;
int qtyY = 2;
for (int i = 0; i < qtyX; i++) {
for (int j = 0; j < qtyY; j++) {
RectangleGeometry myRectangleGeometry = new RectangleGeometry();
myRectangleGeometry.Rect = new Rect(((length + 1) * i), ((height + 1) * j), length, height);
this.RegisterName(
"MyAnimatedRectangleGeometry", myRectangleGeometry);
Path myPath = new Path();
myPath.Fill = Brushes.Blue;
myPath.Data = myRectangleGeometry;
RectAnimation myRectAnimation = new RectAnimation();
myRectAnimation.Duration = TimeSpan.FromSeconds(0.5);
myRectAnimation.FillBehavior = FillBehavior.HoldEnd;
myRectAnimation.From = new Rect(((length + 1) * i), ((height + 1) * j), length /2, height/2);
Storyboard.SetTargetName(myRectAnimation, "MyAnimatedRectangleGeometry");
Storyboard.SetTargetProperty(
myRectAnimation, new PropertyPath(RectangleGeometry.RectProperty));
Storyboard ellipseStoryboard = new Storyboard();
ellipseStoryboard.Children.Add(myRectAnimation);
myPath.Loaded += delegate (object s, RoutedEventArgs r) {
ellipseStoryboard.Begin(this);
};
MyCanvas.Children.Add(myPath);
}
}
}
僅供參考-出於性能目的,我需要使用RectangleGeometry.Rect
。
您不需要情節提要。 只需將動畫直接應用於RectangleGeometry:
myRectangleGeometry.BeginAnimation(RectangleGeometry.RectProperty, myRectAnimation);
完整的內循環主體:
var myRectangleGeometry = new RectangleGeometry(
new Rect(((length + 1) * i), ((height + 1) * j), length, height));
var myPath = new Path
{
Fill = Brushes.Blue,
Data = myRectangleGeometry
};
var myRectAnimation = new RectAnimation
{
Duration = TimeSpan.FromSeconds(0.5),
From = new Rect(((length + 1) * i), ((height + 1) * j), length / 2, height / 2)
};
myRectangleGeometry.BeginAnimation(RectangleGeometry.RectProperty, myRectAnimation);
MyCanvas.Children.Add(myPath);
為了完整起見,要使其與情節提要板一起使用,請使用Target而不是TargetName:
Storyboard.SetTarget(myRectAnimation, myRectangleGeometry);
您需要為每個幾何圖形提供唯一的名稱...
this.RegisterName(
"MyAnimatedRectangleGeometry" + someUniqueValue, myRectangleGeometry);
其中someUniqueValue
是在內部循環的每次迭代中采用新值的變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.