Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Out of Bounds Text Drawing #304

Merged
merged 2 commits into from
Oct 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 33 additions & 7 deletions src/ImageSharp.Drawing/Processing/GradientBrush.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ internal abstract class GradientBrushApplicator<TPixel> : BrushApplicator<TPixel

private readonly MemoryAllocator allocator;

private readonly int scalineWidth;
private readonly int scanlineWidth;

private readonly ThreadLocalBlenderBuffers<TPixel> blenderBuffers;

Expand All @@ -84,13 +84,14 @@ protected GradientBrushApplicator(
GradientRepetitionMode repetitionMode)
: base(configuration, options, target)
{
// TODO: requires colorStops to be sorted by position.
// Use Array.Sort with a custom comparer.
this.colorStops = colorStops;

// Ensure the color-stop order is correct.
InsertionSort(this.colorStops, (x, y) => x.Ratio.CompareTo(y.Ratio));
this.repetitionMode = repetitionMode;
this.scalineWidth = target.Width;
this.scanlineWidth = target.Width;
this.allocator = configuration.MemoryAllocator;
this.blenderBuffers = new ThreadLocalBlenderBuffers<TPixel>(this.allocator, this.scalineWidth);
this.blenderBuffers = new ThreadLocalBlenderBuffers<TPixel>(this.allocator, this.scanlineWidth);
}

internal TPixel this[int x, int y]
Expand Down Expand Up @@ -135,15 +136,16 @@ protected GradientBrushApplicator(

float onLocalGradient = (positionOnCompleteGradient - from.Ratio) / (to.Ratio - from.Ratio);

// TODO: This should use premultiplied vectors to avoid bad blends e.g. red -> brown <- green.
return new Color(Vector4.Lerp((Vector4)from.Color, (Vector4)to.Color, onLocalGradient)).ToPixel<TPixel>();
}
}

/// <inheritdoc />
public override void Apply(Span<float> scanline, int x, int y)
{
Span<float> amounts = this.blenderBuffers.AmountSpan.Slice(0, scanline.Length);
Span<TPixel> overlays = this.blenderBuffers.OverlaySpan.Slice(0, scanline.Length);
Span<float> amounts = this.blenderBuffers.AmountSpan[..scanline.Length];
Span<TPixel> overlays = this.blenderBuffers.OverlaySpan[..scanline.Length];
float blendPercentage = this.Options.BlendPercentage;

// TODO: Remove bounds checks.
Expand Down Expand Up @@ -221,5 +223,29 @@ protected override void Dispose(bool disposing)

return (localGradientFrom, localGradientTo);
}

/// <summary>
/// Provides a stable sorting algorithm for the given array.
/// <see cref="Array.Sort(Array, System.Collections.IComparer?)"/> is not stable.
/// </summary>
/// <typeparam name="T">The type of element to sort.</typeparam>
/// <param name="collection">The array to sort.</param>
/// <param name="comparison">The comparison delegate.</param>
private static void InsertionSort<T>(T[] collection, Comparison<T> comparison)
{
int count = collection.Length;
for (int j = 1; j < count; j++)
{
T key = collection[j];

int i = j - 1;
for (; i >= 0 && comparison(collection[i], key) > 0; i--)
{
collection[i + 1] = collection[i];
}

collection[i + 1] = key;
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ void Draw(IEnumerable<DrawingOperation> operations)
for (int row = firstRow; row < end; row++)
{
int y = startY + row;
Span<float> span = buffer.DangerousGetRowSpan(row)[offsetSpan..];
Span<float> span = buffer.DangerousGetRowSpan(row).Slice(offsetSpan, Math.Min(buffer.Width - offsetSpan, source.Width));
app.Apply(span, startX, y);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -887,12 +887,48 @@ public void CanDrawTextVerticalMixed<TPixel>(TestImageProvider<TPixel> provider)
comparer: ImageComparer.TolerantPercentage(0.002f));
}

[Theory]
[WithBlankImage(200, 200, PixelTypes.Rgba32)]
public void CanRenderTextOutOfBoundsIssue301<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : unmanaged, IPixel<TPixel>
=> provider.VerifyOperation(
ImageComparer.TolerantPercentage(0.01f),
img =>
{
Font font = CreateFont(TestFonts.OpenSans, 70);

const string txt = "V";
FontRectangle size = TextMeasurer.MeasureBounds(txt, new TextOptions(font));

img.Mutate(x => x.Resize((int)size.Width, (int)size.Height));

RichTextOptions options = new(font)
{
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
Origin = new Vector2(size.Width / 2, size.Height / 2)
};

LinearGradientBrush brush = new(
new PointF(0, 0),
new PointF(20, 20),
GradientRepetitionMode.Repeat,
new ColorStop(0, Color.Red),
new ColorStop(0.5f, Color.Green),
new ColorStop(0.5f, Color.Yellow),
new ColorStop(1f, Color.Blue));

img.Mutate(m => m.DrawText(options, txt, brush));
},
false,
false);

private static string Repeat(string str, int times) => string.Concat(Enumerable.Repeat(str, times));

private static string ToTestOutputDisplayText(string text)
{
string fnDisplayText = text.Replace("\n", string.Empty);
return fnDisplayText.Substring(0, Math.Min(fnDisplayText.Length, 4));
return fnDisplayText[..Math.Min(fnDisplayText.Length, 4)];
}

private static Font CreateFont(string fontName, float size)
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.