JVimes JVimes - 25 days ago 6
C# Question

Fit Border around arbitrary Path

I have a Path based on a group of rectangle/ellipse Geometry. When I put an auto-sized Border around it, the border shrinks to fit the RectangleGeometry but does something weird with the EllipseGeometry, as shown below. Anyone know how to fix it so the Border (shown in blue) fits snugly around the whole thing?

Ultimately, I want a Border or a Panel that fits an arbitrary, runtime-generated Path (including the stroke thickness), and I need the geometry size maintained.

screenshot

Sample code:

<Border BorderBrush="Blue" BorderThickness="2"
HorizontalAlignment="Center" VerticalAlignment="Center">
<Path Stroke="Orange" StrokeThickness="5" Fill="Red">
<Path.Data>
<GeometryGroup>
<EllipseGeometry Center="-10,-10" RadiusX="12" RadiusY="12" />
<EllipseGeometry Center="70,0" RadiusX="70" RadiusY="10">
<EllipseGeometry.Transform>
<RotateTransform Angle="-25" CenterX="50" CenterY="0" />
</EllipseGeometry.Transform>
</EllipseGeometry>
<RectangleGeometry Rect="0,0,100,100" />
</GeometryGroup>
</Path.Data>
</Path>
</Border>

Answer

You may set the Path's Stretch property and bind its Width to the Width of the Bounds of the Geometry:

<Path ... Stretch="Uniform"
          Width="{Binding Data.Bounds.Width, RelativeSource={RelativeSource Self}}">
    ...
</Path>

However, that doesn't maintain size if there's a stroke thickness. An alternative that does: put the Border into a Canvas (which does not resize its child elements at all), and do not set the Path's Width:

<Canvas>
    <Border BorderBrush="Blue" BorderThickness="2">
        <Path ... Stretch="Uniform">
            ...
        </Path>
    </Border>
</Canvas>