Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

c# - Creating Diagonal Pattern in WPF

I want to create diagonal hatch pattern in WPF. I am using following XAML code to generate 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 the after filling shape with this pattern, I am getting small gap between two lines. Can anyone suggest a way to avoid that small gap?

Generate Output

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A DrawingBrush would be much simpler than a VisualBrush.

In addition to the central diagonal line, this one draws two additional lines (which may of course be shorter) to cover the top right and bottom left corners of the Brush tile:

<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 the answer given by Balázs, you may also set the Brush's Transform property, and use e.g. a single 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...