wpfdrawingbrush

wpf. Easy way to hide tile brush overflow


I use DrawingBrush to show drag marker - dotted line.

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

Problem - cannot use it with Height=auto, dot-tiles may be sliced:

enter image description here

Is there an easy way to hide incomplete tiles?


Solution

  • You may achieve the desired result by a simple custom FrameworkElement, which only draws full circles that fit into the element's width and height:

    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);
                }
            }
        }
    }