Creating a diagonal pattern in WPF

I want to create a diagonal hatch pattern in WPF. I use the following XAML code to create it:

<VisualBrush x:Key="HatchBrushnew" TileMode="Tile" Viewport="0,0,30,30" ViewportUnits="Absolute" Viewbox="0,0,30,30" ViewboxUnits="Absolute"> <VisualBrush.Visual> <Canvas> <Path Stroke="Gray" StrokeThickness="0.1cm" > <Path.Data> <LineGeometry StartPoint="0,0" EndPoint="30,30" /> </Path.Data> </Path> </Canvas> </VisualBrush.Visual> </VisualBrush> 

But after filling out the form with this drawing, I get a small gap between the two lines. Can anyone suggest a way to avoid this small gap?

Generate output

+5
source share
2 answers

A DrawingBrush would be much simpler than a VisualBrush .

In addition to the central diagonal line, he draws two additional lines (which can, of course, be shorter) to cover the upper right and lower left corners of the brush:

 <DrawingBrush x:Key="HatchBrush" TileMode="Tile" Viewport="0,0,30,30" ViewportUnits="Absolute" Viewbox="0,0,30,30" ViewboxUnits="Absolute"> <DrawingBrush.Drawing> <GeometryDrawing> <GeometryDrawing.Pen> <Pen Brush="Black" Thickness="5"/> </GeometryDrawing.Pen> <GeometryDrawing.Geometry> <Geometry>M0,0 L30,30 M15,-15 L45,15 M-15,15 L15,45</Geometry> </GeometryDrawing.Geometry> </GeometryDrawing> </DrawingBrush.Drawing> </DrawingBrush> 

As shown in BalΓ‘zs answer, you can also set the Brush Transform property and use, for example, one vertical LineGeometry :

 <DrawingBrush x:Key="HatchBrush" TileMode="Tile" Viewport="0,0,30,30" ViewportUnits="Absolute" Viewbox="0,0,30,30" ViewboxUnits="Absolute"> <DrawingBrush.Transform> <RotateTransform Angle="45"/> </DrawingBrush.Transform> <DrawingBrush.Drawing> <GeometryDrawing> <GeometryDrawing.Pen> <Pen Brush="Black" Thickness="5"/> </GeometryDrawing.Pen> <GeometryDrawing.Geometry> <LineGeometry StartPoint="0,15" EndPoint="30,15"/> </GeometryDrawing.Geometry> </GeometryDrawing> </DrawingBrush.Drawing> </DrawingBrush> 
+6
source

You can use VisualBrush.Transform :

 <VisualBrush x:Key="HatchBrushnew" TileMode="Tile" Viewport="0,0,30,30" ViewportUnits="Absolute" Viewbox="0,0,30,30" ViewboxUnits="Absolute"> <VisualBrush.Transform> <RotateTransform Angle="135" CenterX=".5" CenterY=".5" /> </VisualBrush.Transform> <VisualBrush.Visual> <Canvas> <Path Stroke="Gray" StrokeThickness="0.1cm" > <Path.Data> <LineGeometry StartPoint="15,0" EndPoint="15,30" /> </Path.Data> </Path> </Canvas> </VisualBrush.Visual> </VisualBrush> 

And the result:

enter image description here

This looks a bit rarer, you can play VisualBrush.Viewport with the values ​​of VisualBrush.Viewport to fix this. Since we rotate 135 degrees, the interval is actually sqrt (2) times the original, you can use it as a hint.

+2
source

Source: https://habr.com/ru/post/1265170/


All Articles