1

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?

Daap
  • 345
  • 4
  • 10
  • 1
    Try isstroked true on your linesegments – Andy Mar 05 '21 at 22:08
  • That's it! This is the problem when turning XAML into code, sometimes the default values assumed in XAML have to be entered in code constructors and if you don't know the default (like me here)... Thanks! – Daap Mar 05 '21 at 22:45

1 Answers1

0

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.

Daap
  • 345
  • 4
  • 10