20 private readonly
object _presentSync =
new();
23 private WriteableBitmap? _bitmap;
26 private SKImage? _currentImage;
27 private SKRectI _pendingSourceRect;
28 private bool _blitScheduled;
31 private readonly ConcurrentQueue<SKImage> _toDispose =
new();
33 private bool _disposed;
42 Math.Max(1, (int)control.Bounds.
Width),
43 Math.Max(1, (int)control.Bounds.
Height),
44 initialSizeAvailable: false)
46 _control = control ??
throw new ArgumentNullException(nameof(control));
47 _control.SizeChanged += OnSizeChanged;
50 private void OnSizeChanged(
object? sender, global::Avalonia.Controls.SizeChangedEventArgs e)
63 var w = (int)_control.Bounds.Width;
64 var h = (int)_control.Bounds.Height;
77 public override void Present(SKImage bufferImage, SKRectI bufferRect, SKRect destRect)
79 var sourceRect = SKRectI.Intersect(
87 if (sourceRect.IsEmpty)
89 bufferImage.Dispose();
99 bufferImage.Dispose();
103 var old = _currentImage;
104 _currentImage = bufferImage;
106 if (!ReferenceEquals(old, _currentImage) && old is not
null)
107 _toDispose.Enqueue(old);
109 _pendingSourceRect = Union(_pendingSourceRect, sourceRect);
110 scheduleBlit = !_blitScheduled;
111 _blitScheduled =
true;
117 Dispatcher.UIThread.Post(BlitAndInvalidate, DispatcherPriority.Render);
120 private void BlitAndInvalidate()
129 _blitScheduled =
false;
134 sourceRect = _pendingSourceRect;
135 _pendingSourceRect = SKRectI.Empty;
136 _blitScheduled =
false;
147 if (w <= 0 || h <= 0)
150 var imageBounds =
new SKRectI(
156 sourceRect = SKRectI.Intersect(sourceRect, imageBounds);
158 if (sourceRect.IsEmpty)
162 var bitmap = _bitmap;
164 if (bitmap ==
null || bitmap.PixelSize.Width != w || bitmap.PixelSize.Height != h)
168 bitmap =
new WriteableBitmap(
171 PixelFormat.Bgra8888,
175 sourceRect = imageBounds;
181 using (var fb = bitmap.Lock())
183 var info =
new SKImageInfo(
186 SKColorType.Bgra8888,
189 var destinationOffset = checked((sourceRect.Top * fb.RowBytes) + (sourceRect.Left * 4));
190 var destination = IntPtr.Add(fb.Address, destinationOffset);
192 copied = img.ReadPixels(
203 _control.SetBitmap(bitmap);
204 _control.InvalidateVisual();
208 DisposeStaleImages();
212 private static SKRectI Union(SKRectI left, SKRectI right)
221 Math.Min(left.Left, right.Left),
222 Math.Min(left.Top, right.Top),
223 Math.Max(left.Right, right.Right),
224 Math.Max(left.Bottom, right.Bottom));
227 private void DisposeStaleImages()
229 while (_toDispose.TryDequeue(out var stale))
238 SKImage? currentImage;
247 currentImage = _currentImage;
248 _currentImage =
null;
249 _pendingSourceRect = SKRectI.Empty;
250 _blitScheduled =
false;
253 _control.SizeChanged -= OnSizeChanged;
255 DisposeStaleImages();
257 currentImage?.Dispose();
262 GC.SuppressFinalize(
this);