问题描述
此代码段有效:
<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,3" />
<Linesegment Point="0,3" />
</PathSegmentCollection>
</Pathfigure>
</PathGeometry>
</GeometryDrawing.Geometry>
</GeometryDrawing>
</DrawingImage.Drawing>
</DrawingImage>
</Image.source>
</Image>
它显示的图像带有由 Pen
中的 GeometryDrawing
定义的 AliceBlue 边框,无论是在 VS Designer 中还是在编译的应用程序中。
现在我想在代码中做同样的事情,但除了 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,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
奇迹般地没有被应用。我在这里错过了什么?
解决方法
正如 Andy 在评论中指出的,Segment
带有一个 IsStroked 构造函数参数,该参数需要设置为 true
。在 XAML 中,此值默认为 true
。