跳至正文
OpenAgentSkill
浏览已开放 · 目录记录日期 2026-11-21 · 自动更新和账户服务暂时关闭。
其他技能

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 · 已有静态检查记录

安装与使用

运行命令前先阅读来源与依赖说明。复制命令不会自动安装或执行。

npx skills add linuxdevel/Avalonia-skills --skill avalonia-interop-rendering

技能说明


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?

NeedUse
Draw shapes/text in a controlRender(DrawingContext) (other skills)
Raw SkiaSharp calls (SKCanvas, shaders, SKPath effects)ICustomDrawOperation + ISkiaSharpApiLeaseFeature
Animation/redraw loop on the render thread, independent of UI threadComposition custom visual (CompositionCustomVisualHandler)
Animate offset/opacity/scale of an existing control on the compositorComposition implicit/explicit animations
Own OpenGL sceneOpenGlControlBase
Per-pixel CPU imageWriteableBitmap + Lock()
Real native widget (HWND, NSView, X11 window) inside the treeNativeControlHost
Avalonia inside another UI toolkitWinForms 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;
   
阅读完整来源 ↗