如何解决WPF GeometryDrawing Pen 无法从代码中工作
此代码段有效:
<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
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。