用纯色或透明的笔触绘制WPF多边形

时间:2019-04-19 08:06:59

标签: c# wpf polygon draw stroke

我需要在WPF中创建一个通用三角形,以指示坐标,笔触以及笔触和填充区域的颜色。问题是我想将笔划的颜色也表示为“透明”,这意味着要使用同一个坐标,我想在此形状内绘制一个透明的笔划,以替换其粗细的填充颜色,但是似乎不可能(我发现对Triangle和Rectangle形状有一个相同的问题,但是用Polygon却不起作用:Drawing a WPF shape, as a Rectangle: StrokeThickness halve if Stroke is Transparent)。 我现在使用的代码包括一个剪辑,因为笔划在坐标轮廓的内部和外部都变大了,我需要删除外部的部分,以及一些转换器以正确的方式给出点数组:

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

我现在所拥有的是:

current result

我想要的是:

wanted result

注意:对于发布的两个示例,第一个图像的笔划和填充区域均具有纯色,第二个图像的笔划具有透明性,而填充区域具有纯色(这是问题所在),第三幅图像的笔划和填充区域均具有单色填充区域透明。所有图像的坐标和StrokeThickness值都相同。

感谢帮助!

1 个答案:

答案 0 :(得分:0)

从@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);
}