Create VisualBrush by code behind

2019-08-29 04:46发布

I have this example as XAML:

<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>

I need to write the same in code behind but I've been able to do only this:

            VisualBrush vb = new VisualBrush();
        vb.Viewport = new Rect(0, 0, 5, 5);
        vb.TileMode = TileMode.Tile;

Honestly I dunno how to write the Path Data. How can I do this?

1条回答
Rolldiameter
2楼-- · 2019-08-29 05:17

You could write

vb.Visual = new Path
{
    Data = Geometry.Parse("M 0 5 L 5 0 M -2 2 L 2 -2 M 3 7 L 7 3"),
    Stroke = new SolidColorBrush(Color.FromArgb(0x80, 0xff, 0xff, 0xff))
};

However, you don't need to use a VisualBrush at all.

The XAML below shows how to use a DrawingBrush with two drawings to get the hatch pattern on top of a solid color background.

<DrawingBrush x:Key="HatchBrush" TileMode="Tile"
              Viewport="0,0,5,5" ViewportUnits="Absolute"
              Viewbox="0,0,5,5" ViewboxUnits="Absolute">
    <DrawingBrush.Drawing>
        <DrawingGroup>
            <GeometryDrawing Brush="DarkCyan">
                <GeometryDrawing.Geometry>
                    <RectangleGeometry Rect="0,0,5,5"/>
                </GeometryDrawing.Geometry>
            </GeometryDrawing>
            <GeometryDrawing Geometry="M0,5 L5,0 M-2,2 L2,-2 M3,7 L7,3">
                <GeometryDrawing.Pen>
                    <Pen Brush="#80ffffff" Thickness="1"/>
                </GeometryDrawing.Pen>
            </GeometryDrawing>
        </DrawingGroup>
    </DrawingBrush.Drawing>
</DrawingBrush>
查看更多
登录 后发表回答