Skip to content

Commit

Permalink
Fix crash when rendering MonoGame in Avalonia
Browse files Browse the repository at this point in the history
  • Loading branch information
macabrett committed Jan 25, 2024
1 parent 3a1e166 commit 510b674
Showing 1 changed file with 8 additions and 1 deletion.
9 changes: 8 additions & 1 deletion UI/AvaloniaInterop/MonoGameControl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,8 @@ public override void Render(DrawingContext context) {
this._stopwatch.Restart();
this.RunFrame();

using (var bitmapLock = this._bitmap.Lock()) {
try {
using var bitmapLock = this._bitmap.Lock();
var size = bitmapLock.RowBytes * bitmapLock.Size.Height;
if (this._bufferData.Length != size) {
this._bufferData = new byte[size];
Expand All @@ -120,6 +121,12 @@ public override void Render(DrawingContext context) {
device.GetBackBufferData(this._bufferData);
Marshal.Copy(this._bufferData, 0, bitmapLock.Address, this._bufferData.Length);
}
catch {
// If we've got an exception in this block, there's a good chance resetting the graphics
// device will fix the issue. It usually means the size of the device doesn't match the
// bitmap size.
this.ResetDevice(device, this.Bounds.Size);
}

if (!this.TryDrawBitmap(context) && game.CurrentScene is { } scene) {
context.DrawRectangle(scene.BackgroundColor.ToAvaloniaBrush(), null, new Rect(this.Bounds.Size));
Expand Down

0 comments on commit 510b674

Please sign in to comment.