1

这个片段有效:

  <Image Canvas.Left="50" Canvas.Top="0" Width="40" Height="30" ClipToBounds="False">
    <Image.Source>
      <DrawingImage>
        <DrawingImage.Drawing>
          <GeometryDrawing>
            <GeometryDrawing.Pen>
              <Pen Brush="AliceBlue" Thickness=".05" />
            </GeometryDrawing.Pen>
            <GeometryDrawing.Brush>
              <ImageBrush ImageSource="pack://application:,,,/MyApp;component/Resources/SomePicture.png" />
            </GeometryDrawing.Brush>
            <GeometryDrawing.Geometry>
              <PathGeometry>
                <PathFigure StartPoint="0,3" IsClosed="True" IsFilled="True">
                  <PathSegmentCollection>
                    <LineSegment Point="0,0" />
                    <LineSegment Point="3,0" />
                    <LineSegment Point="3,3" />
                    <LineSegment Point="0,3" />
                  </PathSegmentCollection>
                </PathFigure>
              </PathGeometry>
            </GeometryDrawing.Geometry>
          </GeometryDrawing>
        </DrawingImage.Drawing>
      </DrawingImage>
    </Image.Source>
  </Image>

它在 VS Designer 和编译的应用程序中显示带有 AliceBlue 边框的图像,由 中定义PenGeometryDrawing

现在我想在代码中做同样的事情,但除了Pen.

PathFigure pathFigure = new PathFigure() {
    StartPoint = new Point(0, 3),
    IsClosed = true,
    IsFilled = true,
};
pathFigure.Segments.Add(new LineSegment(new Point(0,0)));
pathFigure.Segments.Add(new LineSegment(new Point(3,0)));
pathFigure.Segments.Add(new LineSegment(new Point(3,3)));
pathFigure.Segments.Add(new LineSegment(new Point(0,3)));
PathGeometry geometryImage = new PathGeometry();
geometryImage.Figures.Add(pathFigure);
DrawingImage drawingImage = new DrawingImage(new GeometryDrawing() {
    Pen = new Pen(Brushes.Red, 1), // Pen is not applied!
    Brush = new ImageBrush(bitmap), // A previously loaded BitmapSource
    Geometry = geometryImage,
});
drawingImage.Freeze();
Image image = new() { // In case you wonder, this is valid now in C#
    ClipToBounds = false,
    Stretch = Stretch.Fill,
    Source = drawingImage,
};

这再现了与 XAML 示例完全相同的图像,但Pen奇迹般地没有应用。我在这里想念什么?

4

1 回答 1

0

正如 Andy 在评论中指出的那样,Segments 带有一个 IsStroked 构造函数参数,需要将其设置为true。在 XAML 中,此值默认为true.

于 2021-03-05T22:46:55.687 回答