在 WPF 程序中使用矢量图
我们可以在 WPF 程序中全面地使用矢量图,除了少量特别精细的大图之外,软件内的图标等都可以使用由 Geometry 描述的矢量图。
DrawingImage
DrawingImage 继承自 ImageSource,所以 DrawingImage 可以作为 Image 的 Source,DrawingImage 对象有一个 Drawing 类型的属性 Drawing。
Drawing
Drawing 是描述 2D 绘图的抽象类,系统提供的派生类包括:
- System.Windows.Media.DrawingGroup
- System.Windows.Media.GeometryDrawing
- System.Windows.Media.GlyphRunDrawing
- System.Windows.Media.ImageDrawing
- System.Windows.Media.VideoDrawing
其中 DrawingGroup 和 GeometryDrawing 比较常用。
DrawingGroup 作为 DrawingImage 的 Drawing
下面的示例中,使用了三个 LineGeometry 和一个 RectangleGeometry,使用了两种不同的颜色。注意,针对 LineGeomtry,一定要设置 GeometryDrawing 的 Pen,否则无法呈现出来。
<DrawingImage> <DrawingImage.Drawing> <DrawingGroup> <GeometryDrawing> <GeometryDrawing.Pen> <Pen Thickness="2" Brush="Teal"/> </GeometryDrawing.Pen> <GeometryDrawing.Geometry> <LineGeometry StartPoint="0,3" EndPoint="15,3"/> </GeometryDrawing.Geometry> </GeometryDrawing> <GeometryDrawing> <GeometryDrawing.Pen> <Pen Thickness="2" Brush="Teal"/> </GeometryDrawing.Pen> <GeometryDrawing.Geometry> <LineGeometry StartPoint="0,6" EndPoint="15,6"/> </GeometryDrawing.Geometry> </GeometryDrawing> <GeometryDrawing> <GeometryDrawing.Pen> <Pen Thickness="2" Brush="Teal"/> </GeometryDrawing.Pen> <GeometryDrawing.Geometry> <LineGeometry StartPoint="0,9" EndPoint="15,9"/> </GeometryDrawing.Geometry> </GeometryDrawing> <GeometryDrawing Brush="Crimson"> <GeometryDrawing.Geometry> <RectangleGeometry Rect="17,2 22,8"></RectangleGeometry> </GeometryDrawing.Geometry> </GeometryDrawing> </DrawingGroup> </DrawingImage.Drawing> </DrawingImage>
GeometryDrawing 作为 DrawingImage 的 Drawing
下面使用到 PathGeometry,然后该 PathGeometry 作为资源被 GeometryDrawing 使用。
<!--下载--> <PathGeometry x:Key="DownloadIconGeometry" Figures="M40.909,0 V44.444 H27.272 L56.818,77.777 86.363,44.444 H72.727 V0 Z M9.090,66.666 V100 H109.090 V66.666 H100.000 V88.888 H18.181 V66.666 Z"/> <DrawingImage x:Key="DownloadImage"> <DrawingImage.Drawing> <GeometryDrawing Brush="{DynamicResource IconAccentBrush}" Geometry="{DynamicResource DownloadIconGeometry}"/> </DrawingImage.Drawing> </DrawingImage>
而 GeometryDrawing 的形状用 Geometry 来描述,那么 Geometry 又是什么呢?
Geometry 的派生类
- System.Windows.Media.CombinedGeometry
- System.Windows.Media.EllipseGeometry
- System.Windows.Media.GeometryGroup
- System.Windows.Media.LineGeometry
- System.Windows.Media.PathGeometry
- System.Windows.Media.RectangleGeometry
- System.Windows.Media.StreamGeometry