【问题标题】:WPF Rotate line with angle from center pointWPF从中心点角度旋转线
【发布时间】:2017-12-12 00:10:55
【问题描述】:

我正在尝试使用 WPF 和 c# 绘制线条并面临以下问题。

成像我必须画一条固定长度的线,我需要以给定的角度旋转这条线。假设45度。 但条件是我应该从中心点旋转它。 我附上图片以便清晰理解。

谁能帮我写一个C#程序。

【问题讨论】:

  • 您使用什么图像/绘图 API 来渲染线条?或者该行是 WPF 视图并且您正在尝试旋转它?

标签: c# .net wpf xaml


【解决方案1】:

要将线条旋转自定义角度,请对其应用RotateTransform。您可以将RenderTransformOrigin 属性设置为0.5 0.5 以围绕中心点旋转。

<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>

如果角度是固定的(例如始终相同),您可以计算起点和终点的坐标,并在不使用变换的情况下绘制对角线:

<Line X1="0" Y1="0" X2="200" Y2="200" Stroke="Blue" StrokeThickness="2" />

【讨论】:

    【解决方案2】:

    这是一个想法,你需要改进它,把它塑造成你需要的样子

        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>
    

    【讨论】:

      猜你喜欢
      • 2018-06-27
      • 2010-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-13
      • 2013-12-17
      • 1970-01-01
      • 2013-03-04
      相关资源
      最近更新 更多