avalonia-interop-rendering
Use when going beyond Render()/DrawingContext in Avalonia — Composition API (ElementComposition, CompositionCustomVisualHandler, implicit animations), ICustomDrawOperation with direct SkiaSharp access, OpenGlControlBase, WriteableBitmap/ILockedFramebuffer pixel work, NativeControlHost embedding native HWND/NSView, hosting Avalonia in WinForms/WinUI or EmbeddableControlRoot, text-shaping setup (UseSkia + UseHarfBuzz), or choosing/configuring rendering backends (Skia, Wayland, refresh rate).
linuxdevel · Static checks on file
Installation
Read the source and dependencies before running a command. Copying does not install or execute anything.
npx skills add linuxdevel/Avalonia-skills --skill avalonia-interop-renderingAbout this skill
name: avalonia-interop-rendering description: Use when going beyond Render()/DrawingContext in Avalonia — Composition API (ElementComposition, CompositionCustomVisualHandler, implicit animations), ICustomDrawOperation with direct SkiaSharp access, OpenGlControlBase, WriteableBitmap/ILockedFramebuffer pixel work, NativeControlHost embedding native HWND/NSView, hosting Avalonia in WinForms/WinUI or EmbeddableControlRoot, text-shaping setup (UseSkia + UseHarfBuzz), or choosing/configuring rendering backends (Skia, Wayland, refresh rate).
Avalonia Advanced Rendering & Native Interop
Basic Render(DrawingContext), brushes, geometry and animations: see avalonia-custom-controls and avalonia-graphics-animation. Version labels: see avalonia-versions. This skill covers what sits below/beside them.
Which Tool?
| Need | Use |
|---|---|
| Draw shapes/text in a control | Render(DrawingContext) (other skills) |
| Raw SkiaSharp calls (SKCanvas, shaders, SKPath effects) | ICustomDrawOperation + ISkiaSharpApiLeaseFeature |
| Animation/redraw loop on the render thread, independent of UI thread | Composition custom visual (CompositionCustomVisualHandler) |
| Animate offset/opacity/scale of an existing control on the compositor | Composition implicit/explicit animations |
| Own OpenGL scene | OpenGlControlBase |
| Per-pixel CPU image | WriteableBitmap + Lock() |
| Real native widget (HWND, NSView, X11 window) inside the tree | NativeControlHost |
| Avalonia inside another UI toolkit | WinForms host, EmbeddableControlRoot, Avalonia.WinUI (12.1+) |
Composition API
Namespace Avalonia.Rendering.Composition. Compositor objects live on the render thread; UI-thread properties are copied across.
// Entry point: the element's backing CompositionVisual (null until attached to a root)
var visual = ElementComposition.GetElementVisual(control);
var compositor = visual?.Compositor;
Use it from OnAttachedToVisualTree or later — never the constructor.
Custom visual with its own render-thread loop
sealed class SpinnerHandler : CompositionCustomVisualHandler
{
public static readonly object Start = new(), Stop = new();
bool _running; TimeSpan _last; double _angle;
public override void OnMessage(object message) // UI thread -> render thread
{
if (message == Start) { _running = true; _last = CompositionNow; RegisterForNextAnimationFrameUpdate(); }
else if (message == Stop) _running = false;
}
public override void OnAnimationFrameUpdate() // once per frame while registered
{
if (!_running) return;
var now = CompositionNow;
_angle = (_angle + (now - _last).TotalSeconds * 180) % 360;
_last = now;
Invalidate(); // or Invalidate(Rect) for precise dirty rects
RegisterForNextAnimationFrameUpdate(); // must re-register every frame
}
public override void OnRender(ImmediateDrawingContext context)
{
// Draw from state computed in OnAnimationFrameUpdate (e.g. _angle -> position of a marker)
var x = EffectiveSize.X / 2 + Math.Cos(_angle * Math.PI / 180) * 30;
var y = EffectiveSize.Y / 2 + Math.Sin(_angle * Math.PI / 180) * 30;
context.DrawEllipse(Brushes.DodgerBlue, null, new Point(x, y), 8, 8); // as in ControlCatalog sample
}
}
// In the control:
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTree(e);
var compositor = ElementComposition.GetElementVisual(this)?.Compositor;
if (compositor is null) return;
_custom = compositor.CreateCustomVisual(new SpinnerHandler());
ElementComposition.SetElementChildVisual(this, _custom);
_custom.Size = new Vector(Bounds.Width, Bounds.Height); // keep in sync on size change
_custom.SendHandlerMessage(SpinnerHandler.Start);
}
Handler members (all verified): OnMessage, OnAnimationFrameUpdate, OnRender, GetRenderBounds, EffectiveSize, CompositionNow, Invalidate(), Invalidate(Rect), RegisterForNextAnimationFrameUpdate(), RenderClipContains, RenderClipIntersectes (sic).
Implicit animations (animate when a property changes)
var compositor = ElementComposition.GetElementVisual(this)!.Compositor;
var offset = compositor.CreateVector3KeyFrameAnimation();
offset.Target = "Offset";
offset.InsertExpressionKeyFrame(1.0f, "this.FinalValue");
offset.Duration = TimeSpan.FromMilliseconds(400);
var implicitAnims = compositor.CreateImplicitAnimationCollection();
implicitAnims["Offset"] = offset; // sample wraps animations in CreateAnimationGroup()
ElementComposition.GetElementVisual(childControl)!.ImplicitAnimations = implicitAnims;
Explicit: visual.StartAnimation("Opacity", anim), StopAnimation, StartAnimationGroup. CompositionVisual properties: Offset, Opacity, Scale (Vector3D), RotationAngle, CenterPoint, Size (Vector), Visible, ClipToBounds, OpacityMask, Orientation. (12.0+) Translation (Vector3D) — offset applied on top of layout Offset, ideal for transient motion without fighting layout.
ICustomDrawOperation + Skia
Draw with context.Custom(op) from Render(DrawingContext). ICustomDrawOperation : IDisposable, IEquatable<ICustomDrawOperation> — members Bounds, HitTest(Point), Render(ImmediateDrawingContext).
using Avalonia.Platform; using Avalonia.Rendering.SceneGraph; using Avalonia.Skia; using SkiaSharp;
public override void Render(DrawingContext context)
=> context.Custom(new SkOp(new Rect(Bounds.Size), _phase));
sealed class SkOp(Rect bounds, float phase) : ICustomDrawOperation
{
public Rect Bounds { get; } = bounds;
public bool HitTest(Point p) => Bounds.Contains(p);
public bool Equals(ICustomDrawOperation? other) => other is SkOp o && o.Bounds == Bounds && o.phase == phase;
Read the complete source ↗