xaml-csharp-development-skill-for-avalonia

Shapes, Geometry, and Hit Testing

Table of Contents

  1. Scope and APIs
  2. Shape vs PathIcon vs Custom Render
  3. Built-in Shape Controls
  4. Geometry Construction and Reuse
  5. Hit Testing and Bounds
  6. Layout and Performance Notes
  7. Best Practices
  8. Troubleshooting

Scope and APIs

Primary APIs:

Reference source files:

Shape vs PathIcon vs Custom Render

Use the right primitive:

Rule of thumb:

Built-in Shape Controls

Common properties from Shape:

Specialized APIs:

Geometry Construction and Reuse

XAML path data:

<Path xmlns="https://github.com/avaloniaui"
      Stroke="Orange"
      StrokeThickness="2"
      Fill="#2200AEEF"
      Data="M 10,10 L 90,10 90,40 10,40 Z" />

Shared geometry resources:

<UserControl.Resources>
  <StreamGeometry x:Key="BadgeGeometry">M 0,0 L 16,0 16,16 0,16 Z</StreamGeometry>
</UserControl.Resources>

<Path Data="{StaticResource BadgeGeometry}" Fill="LimeGreen" />

Code construction:

using Avalonia.Controls.Shapes;
using Avalonia.Media;

var shape = new Path
{
    Data = Geometry.Parse("M 0,0 L 24,0 12,16 Z"),
    Fill = Brushes.DodgerBlue,
    Stroke = Brushes.Navy,
    StrokeThickness = 1
};

Hit Testing and Bounds

For geometry-driven interaction logic:

var geometry = Geometry.Parse("M 0,0 L 24,0 12,16 Z");
var point = new Avalonia.Point(8, 6);

bool insideFill = geometry.FillContains(point);
bool insideStroke = geometry.StrokeContains(new Pen(Brushes.Black, 2), point);

Useful APIs:

Layout and Performance Notes

For render-intensive scenarios, evaluate custom drawing (references/14-custom-drawing-text-shapes-and-skia.md).

Best Practices

Troubleshooting

  1. Shape not visible:
    • Missing Fill and Stroke.
    • Zero size from layout constraints.
  2. Stroke looks clipped:
    • Tight layout bounds with thick stroke.
    • Geometry exceeds expected bounds.
  3. Dash pattern not rendering as expected:
    • StrokeThickness too small for the dash array scale.
    • Dash array values too fine for current DPI/zoom.
  4. Arc/Sector appears wrong direction:
    • StartAngle + SweepAngle sign/units are incorrect.
    • Input assumes radians instead of degrees.