Parcourir la source

Align bitmap memory to 4 bytes (#17774)

* Align BitmapMemory to four bytes

* Correct RowBytes calculation
Benedikt Stebner il y a 10 mois
Parent
commit
759facea18

+ 5 - 1
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);

+ 20 - 0
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);
+    }
+}

+ 3 - 0
tests/Avalonia.Skia.RenderTests/Avalonia.Skia.RenderTests.csproj

@@ -16,6 +16,9 @@
     <Compile Update="..\Avalonia.RenderTests\Media\EffectTests.cs">
       <Link>Media\EffectTests.cs</Link>
     </Compile>
+    <Compile Update="..\Avalonia.RenderTests\Media\BitmapMemoryTests.cs">
+      <Link>Media\BitmapMemoryTests.cs</Link>
+    </Compile>
   </ItemGroup>
   <ItemGroup>
     <EmbeddedResource Include="..\Avalonia.RenderTests\*\*.ttf" />