自定义Avalonia控件以从其他线程渲染性能问题



我有一个后台线程,它将一些图像渲染到WriteableBitmap。我正在制作一个自定义控件,它将使用这个可写位图并更新每一帧来制作动画。不幸的是,现在将此控件强制为InvalidateVisual()。这起到了作用,但表现相当糟糕。在主窗口上,我订阅了Renderer.SceneInvalidated以记录一些帧速率。

this.Renderer.SceneInvalidated += (s, e) =>
{
_logs.Add((DateTime.Now - _prev).Ticks);
_prev = DateTime.Now;
};

并发现大约7%-10%的帧在30ms内渲染,其他帧在16ms内渲染90%。因此,我正在寻找一个更好的性能解决方案来解决这个问题。

您可以使用自定义绘图操作API直接访问渲染线程上的SKCanvas。

public class CustomSkiaPage : Control
{   
public CustomSkiaPage()
{ 
ClipToBounds = true;
} 

class CustomDrawOp : ICustomDrawOperation
{ 
public CustomDrawOp(Rect bounds)
{   
Bounds = bounds;
}   

public void Dispose()
{   
// No-op in this example
}   
public Rect Bounds { get; }
public bool HitTest(Point p) => false;
public bool Equals(ICustomDrawOperation other) => false;
public void Render(IDrawingContextImpl context)
{   
var canvas = (context as ISkiaDrawingContextImpl)?.SkCanvas;
// draw stuff 
}   
} 
public override void Render(DrawingContext context)
{ 
context.Custom(new CustomDrawOp(new Rect(0, 0, Bounds.Width, Bounds.Height)));
Dispatcher.UIThread.InvokeAsync(InvalidateVisual, DispatcherPriority.Background);
} 
}

最新更新