如果您能够使用 WPF,这非常简单:
在窗口 xaml 中:
<Window x:Class="WpfApplication6.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="600" Width="600">
<Window.Triggers>
<EventTrigger RoutedEvent="Window.Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetName="AnimatedRect"
Storyboard.TargetProperty="(Canvas.Left)"
To="{Binding ElementName=FixedRect, Path=(Canvas.Left)}" Duration="0:0:1"/>
<DoubleAnimation
Storyboard.TargetName="AnimatedRect"
Storyboard.TargetProperty="(Canvas.Top)"
To="{Binding ElementName=FixedRect, Path=(Canvas.Top)}" Duration="0:0:1"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Window.Triggers>
<Canvas>
<Rectangle Name="FixedRect"
StrokeThickness="2"
Stroke="Black"
Width="{Binding R1.Width}"
Height="{Binding R1.Height}"
Canvas.Left="{Binding R1.X}"
Canvas.Top="{Binding R1.Y}"/>
<Rectangle Name="AnimatedRect"
StrokeThickness="2"
Stroke="Black"
Width="{Binding R2.Width}"
Height="{Binding R2.Height}"
Canvas.Left="{Binding R2.X}"
Canvas.Top="{Binding R2.Y}"/>
</Canvas>
</Window>
代码隐藏:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Random rnd = new Random();
Rect r1 = new Rect();
r1.X = rnd.Next(500);
r1.Y = rnd.Next(500);
r1.Width = rnd.Next(50,100);
r1.Height = rnd.Next(50, 100);
R1 = r1;
Rect r2 = new Rect();
r2.X = rnd.Next(500);
r2.Y = rnd.Next(500);
r2.Width = rnd.Next(50, 100);
r2.Height = rnd.Next(50, 100);
R2 = r2;
DataContext = this;
}
public Rect R1 { get; set; }
public Rect R2 { get; set; }
}