WPF GeometryDrawing Pen not working from code

403 Views Asked by At

This snippet works:

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

It shows the image with an AliceBlue border as defined by the Pen in the GeometryDrawing, both in VS Designer as well as in the compiled app.

Now I want to do the same thing in code, but everything works except for the 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,
};

This reproduces the exact same image as the XAML example, except for the Pen that miraculously does not get applied. What am I missing here?

1

There are 1 best solutions below

0
Daap On

As indicated by Andy in the comments, Segments come with an IsStroked constructor parameter that needs to be set to true. In XAML this value is defaulted to true.