Repository navigation
Description
Note
Fixed by #442 for the CPU backend: with that PR the program below prints different pixels: 0 for every case. The apply rectangle of the WebGPU backend (point 3 of the suggested fix) is not changed there.
Prerequisites
- I have written a descriptive issue title
- I have verified that I am running the latest version of ImageSharp.Drawing
- I have verified if the problem exist in both
DEBUGandRELEASEmode - I have searched open and closed issues to ensure it has not already been reported
ImageSharp.Drawing version
main at commit a4e94b8
Other ImageSharp packages and versions
SixLabors.ImageSharp 5.0.0-alpha.0.38, SixLabors.Fonts 3.2.1, SixLabors.PolygonClipper 2.0.0-alpha.0.2
Environment (Operating system, version and so on)
macOS 15.8.3 (arm64)
.NET Framework version
.NET 10 (net10.0)
Description
DrawingCanvas.CreateRegion(Rectangle) returns a canvas whose coordinates are local to the region. The geometry of a draw on it moves by the offset of the region, but gradient brushes, layer effects (SaveLayer with a LayerEffect), and Apply do not:
- a gradient brush is evaluated as if its points were in the coordinates of the root canvas, so the gradient is shifted by the offset of the region against the shape it fills;
- the effect of a layer and the region of
Applyread the pixels at the local rectangle in the coordinates of the root canvas (or of the layer), not at the rectangle of the region, and write the result back at the right place, so the result shows the wrong pixels.
Solid brushes, image brushes, clips, and layers without an effect are placed correctly.
Explanation
A region canvas shares the command batcher of the root canvas. Its state has the offset of the region as DrawingCanvasState.DestinationOffset, and every command records it.
Brushes: DrawingCanvasBatcher<TPixel>.PrepareCommand (Processing/DrawingCanvasBatcher{TPixel}.cs, near line 720) bakes the transform of a command into its brush with Brush.Transform(composition.Transform, ...), and only when that transform is not the identity. The backends place the geometry with the transform and then add the destination offset (FlushScene.TryPrepareFillPath passes destinationOffset to DefaultRasterizer.CreateRasterizableGeometry), and they evaluate brushes at target pixel positions. So the brush never gets the offset. Position-independent brushes are not affected. ImageBrush anchors its texture to the interest rectangle of the command, which already includes the offset, so it is placed correctly.
Layer effects and Apply: both become an apply barrier. FlushScene.ProcessPathCommand (Processing/Backends/FlushScene.cs, near line 1163) computes the rectangle of the apply item as Rectangle.Intersect(command.ApplyCanvasBounds, ToConservativeBounds(rawOutputBounds)). Both rectangles are in the coordinates of the canvas, so for a region canvas the rectangle does not include the offset. DefaultDrawingBackend.ExecuteApplyItem (Processing/Backends/DefaultDrawingBackend.cs, near line 578) reads the source pixels at that rectangle: from the root target as it is, and from a layer target after subtracting the absolute origin of the layer, which is right only for an absolute rectangle. The write-back is a fill of the path of the apply at the destination offset, so it lands at the right place with the pixels of the wrong place. The WebGPU backend computes the rectangle the same way (WebGPUSceneEncoder.TryAppendApplyCommand).
Suggested fix
- Brushes: in
DrawingCanvasBatcher<TPixel>, bake the destination offset of the canvas state into the brush transform as a translation after the command transform (transform * Matrix4x4.CreateTranslation(offset.X, offset.Y, 0)), for fill, stroke, line, and polyline commands, and set the brush-transform flag when the offset is not zero. The offset of the state is not always the destination offset of the command:CreateTextCompositionCommandadds the whole-pixel glyph position to the destination offset of each glyph, while the brush of the text stays in canvas coordinates. The commands therefore need the offset of the state as a value of its own (for example aBrushOffsetthat defaults to the destination offset and that the text commands set to the offset of the state). A canvas over a whole image has a zero offset, so its draws do not change. - Apply and layer effects: in
FlushScene, move the rectangle of the apply item bycommand.DestinationOffsetafter the brush offset is computed, so the item holds an absolute rectangle; inDefaultDrawingBackend.ExecuteApplyItem, subtract the absolute origin of the target in every case (readRect.Offset(-target.AbsoluteLeft, -target.AbsoluteTop)), not only for a layer target. The root target has the origin of its frame, so a root canvas reads the same pixels as before. - WebGPU:
WebGPUSceneEncoder.TryAppendApplyCommandcomputes the rectangle the same way and needs the same change. Point 1 applies to it already, because both backends take the brushes prepared by the batcher.
With points 1 and 2, the program prints 0 for every case on the CPU backend.
#442 makes changes 1 and 2. It does not change the WebGPU backend (point 3), because the WebGPU backend could not be run for that PR.
Notes
- Found in the SVG work, which draws nested viewports on region canvases.
- A canvas created directly over a part of a buffer (
Buffer2DRegionwith a non-zero origin) also has a non-zero destination offset; its gradients are shifted the same way, and point 1 corrects them too. PatternBrushtiles from the origin of the target, so a hatch on a region canvas equals the same draw at the offset on the root canvas, before and after the fix (checked with a test of the same kind as the program).- Text with a gradient brush on a region canvas is shifted the same way; with the suggested fix it equals the draw at the offset.
- The WebGPU backend was not run; its part of the analysis is from reading the code.
Steps to Reproduce
Project file (Repro.csproj). It references a build of main; the path is a placeholder.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Reference Include="SixLabors.ImageSharp.Drawing" HintPath="path/to/SixLabors.ImageSharp.Drawing.dll" />
<PackageReference Include="SixLabors.ImageSharp" Version="5.0.0-alpha.0.38" />
<PackageReference Include="SixLabors.Fonts" Version="3.2.1" />
<PackageReference Include="SixLabors.PolygonClipper" Version="2.0.0-alpha.0.2" />
</ItemGroup>
</Project>Program.cs:
using System.Numerics;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Drawing;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
// Each case draws the same content twice on a 300 x 300 image:
// once on a region canvas at (40, 30), with local coordinates,
// and once on the root canvas, with every coordinate moved by (40, 30).
// The two images should be equal.
Point offset = new(40, 30);
using Image<Rgba32> texture = new(16, 16);
for (int y = 0; y < 16; y++)
{
for (int x = 0; x < 16; x++)
{
texture[x, y] = ((x / 4) + (y / 4)) % 2 == 0 ? new Rgba32(255, 0, 0, 255) : new Rgba32(0, 0, 255, 255);
}
}
ColorStop[] stops = [new(0F, Color.Red), new(1F, Color.Blue)];
Run("solid brush", (canvas, o) =>
canvas.Fill(Brushes.Solid(Color.Red), new RectanglePolygon(o.X + 20, o.Y + 20, 160, 160)));
Run("linear gradient brush", (canvas, o) =>
canvas.Fill(
new LinearGradientBrush(new PointF(o.X + 20, o.Y), new PointF(o.X + 180, o.Y), GradientRepetitionMode.None, stops),
new RectanglePolygon(o.X + 20, o.Y + 20, 160, 160)));
Run("radial gradient brush", (canvas, o) =>
canvas.Fill(
new RadialGradientBrush(new PointF(o.X + 100, o.Y + 100), 80, GradientRepetitionMode.None, stops),
new RectanglePolygon(o.X + 20, o.Y + 20, 160, 160)));
Run("linear gradient brush, scaled", (canvas, o) =>
{
// The translation is outside the scale, so the root draw gets the same scale.
canvas.Save(new DrawingOptions { Transform = Matrix4x4.CreateScale(2F) * Matrix4x4.CreateTranslation(o.X, o.Y, 0) });
canvas.Fill(
new LinearGradientBrush(new PointF(10, 0), new PointF(90, 0), GradientRepetitionMode.None, stops),
new RectanglePolygon(10, 10, 80, 80));
canvas.Restore();
});
Run("image brush", (canvas, o) =>
canvas.Fill(new ImageBrush<Rgba32>(texture), new RectanglePolygon(o.X + 20, o.Y + 20, 160, 160)));
Run("blur layer effect", (canvas, o) =>
{
canvas.SaveLayer(new GraphicsOptions(), new Rectangle(o.X + 20, o.Y + 20, 160, 160), new BlurLayerEffect(4F));
canvas.Fill(Brushes.Solid(Color.Red), new RectanglePolygon(o.X + 50, o.Y + 50, 100, 100));
canvas.Restore();
});
Run("drop shadow layer effect", (canvas, o) =>
{
canvas.SaveLayer(new GraphicsOptions(), new Rectangle(o.X + 20, o.Y + 20, 160, 160), new DropShadowLayerEffect(new Point(6, 6), 3F, Color.Black));
canvas.Fill(Brushes.Solid(Color.Red), new RectanglePolygon(o.X + 50, o.Y + 50, 100, 100));
canvas.Restore();
});
Run("apply", (canvas, o) =>
{
canvas.Fill(Brushes.Solid(Color.Red), new RectanglePolygon(o.X + 20, o.Y + 20, 160, 160));
canvas.Apply(new Rectangle(o.X, o.Y, 100, 100), ctx => ctx.Invert());
});
void Run(string name, Action<DrawingCanvas, Point> draw)
{
using Image<Rgba32> onRegion = new(300, 300, new Rgba32(255, 255, 255, 255));
using Image<Rgba32> atOffset = new(300, 300, new Rgba32(255, 255, 255, 255));
onRegion.Mutate(c => c.Paint(canvas => draw(canvas.CreateRegion(new Rectangle(offset.X, offset.Y, 220, 240)), Point.Empty)));
atOffset.Mutate(c => c.Paint(canvas => draw(canvas, offset)));
int different = 0;
for (int y = 0; y < 300; y++)
{
for (int x = 0; x < 300; x++)
{
if (onRegion[x, y] != atOffset[x, y])
{
different++;
}
}
}
Console.WriteLine($"{name,-32} different pixels: {different}");
}Run with dotnet run -c Release. A Debug build of main gives the same output.
Observed output:
solid brush different pixels: 0
linear gradient brush different pixels: 25600
radial gradient brush different pixels: 21573
linear gradient brush, scaled different pixels: 25600
image brush different pixels: 0
blur layer effect different pixels: 19192
drop shadow layer effect different pixels: 10011
apply different pixels: 4400
Expected output: different pixels: 0 for every case.
Images
Each image shows the draw on the region canvas on the left and the same draw at the offset on the root canvas on the right; both should be equal.
Linear gradient brush: on the region canvas the gradient is shifted by the offset of the region, so the left edge is not pure red.
Blur layer effect: the layer is read at the local rectangle and written back at the region, so the square lands shifted by the offset a second time.
Apply with Invert: the inverted rectangle shows the pixels of the wrong place.

Activity