WPF Rectangle filled with horizontal or vertical l

2019-04-29 14:47发布

问题:

I am trying to create one rectangle filled with Horizontal or Vertical lines. The width of the rectangle is dynamic so I can not use an image brush. Please let me know if anybody knows any solution.

回答1:

I figured out a straight-forward way of doing this; finally, I used following visual brush resources to fill rectangle with horizontal, vertical or dotted vertical lines respectively

   <!--for horizontal lines-->    
   <VisualBrush 
              x:Key="HorizontalLines" 
              TileMode="Tile" Viewport="0,0,4,4" 
              ViewportUnits="Absolute" Viewbox="0,0,10,10"    
              ViewboxUnits="Absolute">
            <VisualBrush.Visual>
                <Canvas>
                    <Path Stroke="Black" Data="M 0 10 l 10 0" />
                </Canvas>
            </VisualBrush.Visual>
        </VisualBrush>

        <!--For vertical lines-->
        <VisualBrush 
              x:Key="VerticalLines" 
              TileMode="Tile" Viewport="0,0,4,4" 
              ViewportUnits="Absolute" Viewbox="0,0,10,10"    
              ViewboxUnits="Absolute">
            <VisualBrush.Visual>
                <Canvas >            
                    <Path Stroke="Black" Data="M 0 0 l 0 10" />                        
                </Canvas>
            </VisualBrush.Visual>
        </VisualBrush>


         <!--For dotted vertical lines-->
        <VisualBrush 
                x:Key="DottedVerticalLinesWithFill" 
                TileMode="Tile" Viewport="0,0,10,10" 
                ViewportUnits="Absolute" Viewbox="0,0,10,10"    
                ViewboxUnits="Absolute">
            <VisualBrush.Visual>
                <Canvas>
                    <Path Stroke="Purple" Data="M 0 5l 0 -10" />
                </Canvas>
            </VisualBrush.Visual>
        </VisualBrush>


回答2:

You can easily do this with a LinearGradientBrush:

  <Rectangle Width="100" Height="100">
     <Rectangle.Fill>
        <LinearGradientBrush SpreadMethod="Reflect" StartPoint="0 0" EndPoint="0 0.05">
           <GradientStop Offset="0.5" Color="Black"/>
           <GradientStop Offset="0.5" Color="White"/>
        </LinearGradientBrush>
     </Rectangle.Fill>
  </Rectangle>

You control line thickness and orientation with the EndPoint property.



回答3:

Have you tried using a TileBrush?



回答4:

ImageBrush derives from TileBrush so you can use the Viewport property to repeat the image. See this MSDN page for an example.



标签: wpf drawing