I am trying to create one sample project to move an ellipse object along a circular path in WPF. For this I used the following equations: x = x0 + R * sin (a), y = y0 + R * cos (a), here (x0, y0) is the center of the circular path, R is the radius of the path, but my ellipse is not moving in a circle, it is moving in a line. where i made mistake?
My XAML source:
<Window x:Class="MyWpfAppSample1.MainWindow"
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"
xmlns:local="clr-namespace:MyWpfAppSample1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800" WindowStartupLocation="CenterOwner">
<Grid>
<Button Content="Start" x:Name="btnStart" Width="100" Height="50" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="100,10,0,0" Click="btnStart_Click"/>
<Button Content="Stop" x:Name="btnStop" Width="100" Height="50" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="210,10,0,0" Click="btnStop_Click"/>
<Ellipse x:Name="myEllipse" Height="10" Width="10" Fill="Aqua" Margin="400,210,0,0" VerticalAlignment="Top" HorizontalAlignment="Left"/>
</Grid>
</Window>
My c# code for XAML:
public partial class MainWindow : Window
{
private double x;
private double y;
private double angle;
private CancellationTokenSource tokenSource;
public MainWindow()
{
InitializeComponent();
}
private void btnStart_Click(object sender, RoutedEventArgs e)
{
tokenSource = new CancellationTokenSource();
var task = Task.Run(() => MoveMyEllipse(tokenSource.Token));
}
private void btnStop_Click(object sender, RoutedEventArgs e)
{
tokenSource.Cancel();
}
private void MoveMyEllipse(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
angle = angle + 0.1;
Invoke(() =>
{
x = myEllipse.Margin.Top + myEllipse.Height * Math.Sin(angle);
y = myEllipse.Margin.Left + myEllipse.Width * Math.Cos(angle);
myEllipse.Margin = new Thickness(x, y, 0, 0);
});
Thread.Sleep(100);
}
}
private void Invoke(Action action)
{
Dispatcher?.Invoke(action);
}
}