首页 > 解决方案 > 用纯色或透明的笔触绘制 WPF 多边形

问题描述

我需要在 WPF 中创建一个通用三角形,指示笔触和填充区域的坐标、笔触和颜色。问题是我想将笔画的透明也指示为颜色,这意味着比使用相同的坐标,我想在这个形状内绘制一个透明笔画,以替换他的厚度填充颜色,但这似乎是不可能的(我发现并解决了 Circle 和 Rectangle 形状的一个棘手问题,但使用 Polygon 它不起作用:绘制一个 WPF 形状,作为 Rectangle: StrokeThickness 减半,如果 Stroke 是透明的)。我现在使用的代码包括一个剪辑,因为笔划在坐标轮廓内部和外部增长部分,我需要删除外部部分,以及一些转换器以正确方式给出点数组:

<UserControl.Clip>
    <PathGeometry>
        <PathFigure StartPoint="{Binding Triangle.Points, Converter={StaticResource PointLocationClipConverter}}" IsClosed="True">
            <PolyLineSegment Points="{Binding Triangle.Points, Converter={StaticResource PointCollectionClipConverter}}" />
        </PathFigure>
    </PathGeometry>
</UserControl.Clip>

<Grid x:Name="_grid">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>

    <Polygon Points="{Binding Triangle.Points, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource PointCollectionConverter}}" Grid.Row="0" Grid.Column="0" Margin="0,0,0,0"
             Width="{Binding ActualWidth, ElementName=_grid}"
             Height="{Binding ActualHeight, ElementName=_grid}"
             Stroke="{Binding Triangle.BorderColorBrush}"
             StrokeThickness="{Binding Triangle.Thick, Converter={StaticResource PoligonThickConverter}}" 
             Fill="{Binding Triangle.BackgroundBrush}" />

</Grid>

我现在拥有的是:

当前结果

我想要的是:

想要的结果

注意:对于发布的两个示例,第一张图像的描边和填充区域具有纯色,第二张图像在描边和填充区域具有纯色(这是问题所在),第三张图像对于描边和填充具有纯色区域。所有图像都具有相同的坐标和 StrokeThickness 值。

感谢帮助!

标签: c#wpfpolygondrawstroke

解决方案


从@Clemens 指示开始,我用一系列变换详细说明了一个解决方案,没有任何几何演算。或多或少的解决方案在这里,我将尝试应用于我的上下文,但最终是:

    <Path MouseLeftButtonUp="PathPolyline_MouseLeftButtonUp"
          StrokeThickness="0" Stroke="Transparent" Fill="Gold" ClipToBounds="False">
        <Path.Data>
            <PathGeometry FillRule="EvenOdd" >
                <PathFigure StartPoint="0,0" IsClosed="True">
                    <PolyLineSegment Points="50,50 0,80"/>
                </PathFigure>
            </PathGeometry>
        </Path.Data>
    </Path>

和 C# 代码中的详细说明将执行以下操作:

private void PathPolyline_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
  Brush brush = Brushes.Black;
  Pen pen = new Pen(brush, 20.0); //thickness double than wanted measure: 20 to reduce 10
  //
  Path path = sender as Path;
  PathGeometry pg = path.Data as PathGeometry;
  PathGeometry pg2 = pg.GetWidenedPathGeometry(pen);
  //
  Transform tr = Transform.Identity;
  PathGeometry pg324 = Geometry.Combine(pg, pg2, GeometryCombineMode.Intersect, tr);
  pg.AddGeometry(pg324);
}

推荐阅读