From 759facea182b7771ce07baf173c52529f4871004 Mon Sep 17 00:00:00 2001 From: Benedikt Stebner Date: Tue, 17 Dec 2024 18:13:49 +0100 Subject: [PATCH] Align bitmap memory to 4 bytes (#17774) * Align BitmapMemory to four bytes * Correct RowBytes calculation --- .../Media/Imaging/BitmapMemory.cs | 6 +++++- .../Media/BitmapMemoryTests.cs | 20 +++++++++++++++++++ .../Avalonia.Skia.RenderTests.csproj | 3 +++ 3 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 tests/Avalonia.RenderTests/Media/BitmapMemoryTests.cs diff --git a/src/Avalonia.Base/Media/Imaging/BitmapMemory.cs b/src/Avalonia.Base/Media/Imaging/BitmapMemory.cs index 1032081b6e..174998a31e 100644 --- a/src/Avalonia.Base/Media/Imaging/BitmapMemory.cs +++ b/src/Avalonia.Base/Media/Imaging/BitmapMemory.cs @@ -14,7 +14,11 @@ internal class BitmapMemory : IDisposable Format = format; AlphaFormat = alphaFormat; Size = size; - RowBytes = (size.Width * format.BitsPerPixel + 7) / 8; + + var bytesPerPixel = (format.BitsPerPixel + 7) / 8; + + RowBytes = 4 * ((size.Width * bytesPerPixel + 3) / 4); + _memorySize = RowBytes * size.Height; Address = Marshal.AllocHGlobal(_memorySize); GC.AddMemoryPressure(_memorySize); diff --git a/tests/Avalonia.RenderTests/Media/BitmapMemoryTests.cs b/tests/Avalonia.RenderTests/Media/BitmapMemoryTests.cs new file mode 100644 index 0000000000..75592660e6 --- /dev/null +++ b/tests/Avalonia.RenderTests/Media/BitmapMemoryTests.cs @@ -0,0 +1,20 @@ +using Avalonia.Media.Imaging; +using Avalonia.Platform; +using Xunit; + +namespace Avalonia.Skia.RenderTests; + +public class BitmapMemoryTests +{ + [InlineData(PixelFormatEnum.Bgr24, AlphaFormat.Opaque)] + [InlineData(PixelFormatEnum.Bgr555, AlphaFormat.Opaque)] + [InlineData(PixelFormatEnum.Bgr565, AlphaFormat.Opaque)] + [InlineData(PixelFormatEnum.BlackWhite, AlphaFormat.Opaque)] + [Theory] + internal void Should_Align_RowBytes_To_Four_Bytes(PixelFormatEnum pixelFormatEnum, AlphaFormat alphaFormat) + { + var bitmapMemory = new BitmapMemory(new PixelFormat(pixelFormatEnum), alphaFormat, new PixelSize(33, 1)); + + Assert.True(bitmapMemory.RowBytes % 4 == 0); + } +} diff --git a/tests/Avalonia.Skia.RenderTests/Avalonia.Skia.RenderTests.csproj b/tests/Avalonia.Skia.RenderTests/Avalonia.Skia.RenderTests.csproj index aedeef4f4c..60082ce2c8 100644 --- a/tests/Avalonia.Skia.RenderTests/Avalonia.Skia.RenderTests.csproj +++ b/tests/Avalonia.Skia.RenderTests/Avalonia.Skia.RenderTests.csproj @@ -16,6 +16,9 @@ Media\EffectTests.cs + + Media\BitmapMemoryTests.cs +