WPF。轻松隐藏瓷砖刷溢出的方法

时间:2015-03-20 07:47:34

标签: wpf drawingbrush

我使用DrawingBrush显示拖动标记 - 虚线。

<Rectangle Height="19" Width="7">
    <Rectangle.Fill>
        <DrawingBrush TileMode="Tile"
                      Viewbox="0,0,2,2"
                      Viewport="0,0,4,4"
                      ViewportUnits="Absolute"
                      ViewboxUnits="RelativeToBoundingBox">
            <DrawingBrush.Drawing>
                <DrawingGroup>
                    <GeometryDrawing Brush="#FF6D6D6D">
                        <GeometryDrawing.Geometry>
                            <EllipseGeometry Center="1,1"
                                             RadiusX="1"
                                             RadiusY="1" />
                        </GeometryDrawing.Geometry>
                    </GeometryDrawing>
                </DrawingGroup>
            </DrawingBrush.Drawing>
        </DrawingBrush>
    </Rectangle.Fill>
</Rectangle>

问题 - 无法将其与Height=auto一起使用,点瓷砖可能会被切片:

enter image description here

是否有一种简单的方法可以隐藏不完整的瓷砖?

1 个答案:

答案 0 :(得分:0)

您可以通过简单的自定义FrameworkElement获得所需的结果,该FrameworkElement仅绘制适合元素宽度和高度的完整圆圈:

public class DragMarker : FrameworkElement
{
    public static readonly DependencyProperty ForegroundProperty =
        Control.ForegroundProperty.AddOwner(typeof(DragMarker));

    public Brush Foreground
    {
        get { return (Brush)GetValue(ForegroundProperty); }
        set { SetValue(ForegroundProperty, value); }
    }

    protected override void OnRender(DrawingContext drawingContext)
    {
        for (int y = 0; y < (int)ActualHeight / 4; y++)
        {
            for (int x = 0; x < (int)ActualWidth / 4; x++)
            {
                drawingContext.DrawEllipse(Foreground, null,
                    new Point(x * 4 + 2, y * 4 + 2), 1, 1);
            }
        }
    }
}