Vinod
Vinod

Reputation: 4352

How to rotate a straight line with one end point fixed in WPF

I want to rotate a line L by moving the end point (X2,Y2) while keeping the start point (X1,Y1) fixed at (0,0). The below code is making the line rotate along the mid point of the line L. Can you help me how to do this.

//XAML
<Window x:Class="SPDisplay.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:SPDisplay"
        mc:Ignorable="d"
        Title="PPI Display" Height="1000" Width="1000">
    <StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center" Name="sp">

        <Line Stroke="Black" StrokeThickness="2" Margin="0" Name="lineSweep"
                X1="0" Y1="0" X2="0" Y2="0"/>       
    </StackPanel>
</Window>

//C# code

using System;
using System.Windows;
using System.Windows.Shapes;
using System.Windows.Media.Animation;

Storyboard sb = new Storyboard();

DoubleAnimation animateY1 = new DoubleAnimation();
animateY1.From = 0;
animateY1.To = 0;
animateY1.Duration = TimeSpan.Parse("0:0:5");

DoubleAnimation animateX1 = new DoubleAnimation();
animateX1.From = 0;
animateX1.To = 0;
animateX1.Duration = TimeSpan.Parse("0:0:5");

DoubleAnimation animateY2 = new DoubleAnimation();
animateY2.From = 200;
animateY2.To = 0;
animateY2.Duration = TimeSpan.Parse("0:0:5");

DoubleAnimation animateX2 = new DoubleAnimation();
animateX2.From = 0;
animateX2.To = 200;
animateX2.Duration = TimeSpan.Parse("0:0:5");

sb.Children.Add(animateY1);
sb.Children.Add(animateX1);

sb.Children.Add(animateY2);
sb.Children.Add(animateX2);

Storyboard.SetTargetName(animateY1, "lineSweep");
Storyboard.SetTargetProperty(animateY1, new PropertyPath(Line.Y1Property));

Storyboard.SetTargetName(animateX1, "lineSweep");
Storyboard.SetTargetProperty(animateX1, new PropertyPath(Line.X1Property));


Storyboard.SetTargetName(animateY2, "lineSweep");
Storyboard.SetTargetProperty(animateY2,new PropertyPath(Line.Y2Property));

Storyboard.SetTargetName(animateX2, "lineSweep");
Storyboard.SetTargetProperty(animateX2, new PropertyPath(Line.X2Property));

sb.Begin(lineSweep);

Upvotes: 0

Views: 389

Answers (1)

Droppy
Droppy

Reputation: 51

The animation is actually doing what you want. The problem is the container you've chosen. If you set Background="Red" for your StackPanel you'll see what's happening. Try Canvas instead of StackPanel.

Upvotes: 1

Related Questions