1
以下代碼繪製一條線,將其旋轉30度左右,將其恢復到其原始位置,將其繞右端旋轉30度,然後重複多次。圍繞不同中心進行連續旋轉?
我該如何對這些旋轉進行排序而不將這條線恢復到原來的位置?第一次旋轉(左端點附近)導致右端點移動;所以我希望下一輪輪換在新的位置。
序列的淨效應應該是使線段「前進」。
(請注意,此代碼使用相同的角度一遍又一遍,但我需要一個解決方案,如果角度每次都是不同的,也將正常工作。)
XAML: -
<UserControl x:Class="Rotation.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
<Grid x:Name="LayoutRoot">
<Canvas Width="500" Height="500">
<Line Name="TheLine" X1="100" Y1="200" X2="200" Y2="200" Stroke="Black" StrokeThickness="5"></Line>
</Canvas>
</Grid>
</UserControl>
代碼: -
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace Rotation
{
public partial class MainPage : UserControl
{
double x1, y1, x2, y2;
public MainPage()
{
InitializeComponent();
for (int i = 0; i < 5; i++)
{
_animations.Add(() => { return rot(true, -30); });
_animations.Add(() => { return rot(false, 30); });
}
_enumerator = _animations.GetEnumerator();
x1 = TheLine.X1;
x2 = TheLine.X2;
y1 = TheLine.Y1;
y2 = TheLine.Y2;
this.Loaded += delegate(object sender, RoutedEventArgs e)
{
RunNextAnimation();
};
}
List<Func<Storyboard>> _animations = new List<Func<Storyboard>>();
IEnumerator<Func<Storyboard>> _enumerator;
public void AnimationCompleted(object sender, EventArgs args)
{
RunNextAnimation();
}
void RunNextAnimation()
{
if (_enumerator.MoveNext())
{
Func<Storyboard> fn = _enumerator.Current;
if (fn != null)
{
Storyboard board = fn();
board.Completed += AnimationCompleted;
board.Begin();
}
}
}
public Storyboard rot(bool aroundLeft, double angle)
{
Storyboard board = new Storyboard();
int duration = 5;
if (true)
{
RotateTransform rot = new RotateTransform();
if (aroundLeft)
{
rot.CenterX = x1;
rot.CenterY = y1;
}
else
{
rot.CenterX = x2;
rot.CenterY = y2;
}
TheLine.RenderTransform = rot;
DoubleAnimation an = new DoubleAnimation();
an.Duration = new Duration(new TimeSpan(0, 0, duration));
an.From = 0;
an.To = angle;
board.Children.Add(an);
Storyboard.SetTarget(an, TheLine);
Storyboard.SetTargetProperty(an, new PropertyPath("(UIElement.RenderTransform).Angle"));
}
return board;
}
}
}