Reputation: 57
I am trying to draw lines using WPF and c# and Facing the below problem.
Imaging I have to draw a line with fixed length, I need to rotate this line with the given angle. suppose 45 degree. But the condition is I should rotate this from center point. I am attaching the image for clean understanding.
Can any one please help me to write a C# program.
Upvotes: 0
Views: 6179
Reputation: 2448
To rotate the line by a custom angle, apply a RotateTransform to it. You can set RenderTransformOrigin property to 0.5 0.5
to rotate around center point.
<Grid Width="200" Height="200">
<Line X1="0" Y1="0" X2="1" Y2="0" Stretch="Uniform" Stroke="Blue" StrokeThickness="2" RenderTransformOrigin="0.5 0.5">
<Line.RenderTransform>
<RotateTransform Angle="45" />
</Line.RenderTransform>
</Line>
</Grid>
If the angle is fixed (e.g. always the same), you can calculate coordinates of the start and end points, and draw a diagonal line without using transform:
<Line X1="0" Y1="0" X2="200" Y2="200" Stroke="Blue" StrokeThickness="2" />
Upvotes: 7
Reputation: 726
here's the idea, you need to improve it, shape it to what you need
private void Rotate()
{
while (Degrees >= 360)
Degrees -= 360;
while (Degrees <= -360)
Degrees += 360;
X1 = 0;
Y1 = 0;
var rad = Degrees * Math.PI / 180;
const int radius = 100;
var sin = Math.Sin(rad);
var cos = Math.Cos(rad);
var tan = Math.Tan(rad);
Y2 = sin * radius;
X2 = cos * radius;
}
XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Orientation="Horizontal" >
<Label Content="Rotation" />
<TextBox Text="{Binding Degrees}" Width="50" Margin="5,5,0,5" HorizontalContentAlignment="Right" VerticalContentAlignment="Center"/>
<Label Content="°" />
<Button Content="Rotate" Margin="5" Command="{Binding RotateCommand}"/>
</StackPanel>
<Grid Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center" >
<Line Stroke="Red" X1="{Binding X1}" X2="{Binding X2}" Y1="{Binding Y1}" Y2="{Binding Y2}"/>
</Grid>
</Grid>
Upvotes: 3