有时,我们为了方便查看WPF图形的样式及比例等,需要一些辅助性的格线,置于图形、图像的背景中。
比如下图,就是为了更清晰地查看折线的图形,我们画了用于标示位置大小的背景格:
那么,怎么绘制这样的格子呢?
为了更通用些,我把它做成资源的形式,放到app.xaml文件中的 <Application.Resources>节内:
<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="Microsoft.Samples.Graphics.app"
Startup="myAppStartingUp">
<Application.Resources>
<DrawingBrush x:Key="MyGridBrushResource" Viewport="0,0,10,10" ViewportUnits="Absolute" TileMode="Tile">
<DrawingBrush.Drawing>
<DrawingGroup>
<DrawingGroup.Children>
<GeometryDrawing Brush="White"><!-- 这里是格子填充颜色 -->
<GeometryDrawing.Geometry>
<RectangleGeometry Rect="0,0,1,1" />
</GeometryDrawing.Geometry>
</GeometryDrawing>
<GeometryDrawing Geometry="M0,0 L1,0 1,0.1, 0,0.1Z" Brush="#CCCCFF" /><!-- 这里是横线 -->
<GeometryDrawing Geometry="M0,0 L0,1 0.1,1, 0.1,0Z" Brush="#CCCCFF" /><!-- 这里是竖线 -->
</DrawingGroup.Children>
</DrawingGroup>
</DrawingBrush.Drawing>
</DrawingBrush>
<!-- 这里是外框线 -->
<Style x:Key="MyGridBorderStyle">
<Setter Property="Border.Background" Value="{StaticResource MyGridBrushResource}"/>
<Setter Property="Border.HorizontalAlignment" Value="Center"/>
<Setter Property="Border.VerticalAlignment" Value="Top"/>
<Setter Property="Border.BorderBrush" Value="Black"/>
<Setter Property="Border.BorderThickness" Value="1"/>
</Style>
</Application.Resources>
</Application>
其中,Viewport="0,0,10,10"中的10,10表示格子的像素宽度、高度值。
使用方法:
// PolylineExample.xaml
<!-- This example shows how to draw Polyline elements. -->
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="BrawDraw.Com.WPF.Graphics.PolylineExample"
WindowTitle="Polyline Example">
<StackPanel>
<StackPanel Margin="10">
<Border Style="{StaticResource MyGridBorderStyle}">
<Canvas Height="400" Width="400">
<Polyline
Points="10,110 60,10 110,110"
Stroke="Black"
StrokeThickness="4" />
<Polyline
Points="10,110 110,110 110,10"
Stroke="Black"
StrokeThickness="4"
Canvas.Left="150" />
</Canvas>
</Border>
</StackPanel>
</StackPanel>
</Page>
C#代码:
// PolylineExample.xaml.cs
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media;
using System.Windows.Media.Animation;
namespace BrawDraw.Com.WPF.Graphics
{
public partial class PolylineExample : Page
{
public PolylineExample()
{
InitializeComponent();
}
}
}