Create a hatch pattern in WPF

守給你的承諾、 提交于 2019-12-04 00:22:26
Anatoliy Nikolaev

You can do it in XAML using VisualBrush. You only need to specify Data values for the Path, for example:

XAML

<Window.Resources>
    <VisualBrush x:Key="MyVisualBrush" TileMode="Tile" Viewport="0,0,15,15" ViewportUnits="Absolute" Viewbox="0,0,15,15" ViewboxUnits="Absolute">
        <VisualBrush.Visual>
            <Grid Background="Black">
                <Path Data="M 0 15 L 15 0" Stroke="Gray" />
                <Path Data="M 0 0 L 15 15" Stroke="Gray" />
            </Grid>
        </VisualBrush.Visual>
    </VisualBrush>
</Window.Resources>

<Grid Background="{StaticResource MyVisualBrush}">
    <Label Content="TEST" Foreground="White" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>

Output

For converting Image to Vector graphics (Path) use Inkscape, which is free and very useful. For more information see this link:

Vectorize Bitmaps to XAML using Potrace and Inkscape

Edit

For better performance, you may Freeze() you Brushes with help of PresentationOptions like this:

<Window x:Class="MyNamespace.MainWindow"
        xmlns:PresentationOptions="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options" ...>

    <VisualBrush x:Key="MyVisualBrush" PresentationOptions:Freeze="True" ... />

Quote from MSDN:

When you no longer need to modify a freezable, freezing it provides performance benefits. If you were to freeze the brush in this example, the graphics system would no longer need to monitor it for changes. The graphics system can also make other optimizations, because it knows the brush won't change.

Here's another approach, for a different style of hatching:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:po="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options"
  Background="Black">

  <Page.Resources>

    <VisualBrush x:Key="HatchBrush" TileMode="Tile"
                 Viewport="0,0,5,5" ViewportUnits="Absolute"
                 Viewbox="0,0,5,5" ViewboxUnits="Absolute"
                 po:Freeze="True">
      <VisualBrush.Visual>
        <Path Data="M 0 5 L 5 0 M -2 2 L 2 -2 M 3 7 L 7 3"
              Stroke="#80ffffff" StrokeEndLineCap="Square"
              RenderOptions.EdgeMode="Aliased" />
      </VisualBrush.Visual>
    </VisualBrush>

  </Page.Resources>

  <Grid Background="{StaticResource HatchBrush}" />

</Page>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!