Skip to content

Commit ead6ac8

Browse files
authored
[SKIA] Don't re-create SKImage on every WriteableBitmap draw call (#18164)
1 parent 920122c commit ead6ac8

File tree

1 file changed

+24
-3
lines changed

1 file changed

+24
-3
lines changed

src/Skia/Avalonia.Skia/WriteableBitmapImpl.cs

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@ namespace Avalonia.Skia
1515
internal class WriteableBitmapImpl : IWriteableBitmapImpl, IDrawableBitmapImpl
1616
{
1717
private static readonly SKBitmapReleaseDelegate s_releaseDelegate = ReleaseProc;
18-
private readonly SKBitmap _bitmap;
18+
private SKBitmap _bitmap;
19+
private SKImage? _image;
20+
private bool _imageValid;
1921
private readonly object _lock = new();
2022

2123
/// <summary>
@@ -119,13 +121,31 @@ public WriteableBitmapImpl(PixelSize size, Vector dpi, PixelFormat format, Alpha
119121
public void Draw(DrawingContextImpl context, SKRect sourceRect, SKRect destRect, SKPaint paint)
120122
{
121123
lock (_lock)
122-
context.Canvas.DrawBitmap(_bitmap, sourceRect, destRect, paint);
124+
{
125+
if (_image == null || !_imageValid)
126+
{
127+
_image?.Dispose();
128+
_image = null;
129+
// NOTE: this does a snapshot of the bitmap. If SKCanvas is not GPU-backed we might want to avoid
130+
// that by force-sharing the pixel data with SKBitmap, but that would require manual pixel
131+
// buffer management
132+
_image = GetSnapshot();
133+
_imageValid = true;
134+
}
135+
context.Canvas.DrawImage(_image, sourceRect, destRect, paint);
136+
}
123137
}
124138

125139
/// <inheritdoc />
126140
public virtual void Dispose()
127141
{
128-
_bitmap.Dispose();
142+
lock (_lock)
143+
{
144+
_image?.Dispose();
145+
_image = null;
146+
_bitmap.Dispose();
147+
_bitmap = null!;
148+
}
129149
}
130150

131151
/// <inheritdoc />
@@ -198,6 +218,7 @@ public void Dispose()
198218
{
199219
_bitmap.NotifyPixelsChanged();
200220
_parent.Version++;
221+
_parent._imageValid = false;
201222
Monitor.Exit(_parent._lock);
202223
_bitmap = null!;
203224
_parent = null!;

0 commit comments

Comments
 (0)