diff --git a/src/ImageSharp.Drawing/ImageSharp.Drawing.csproj b/src/ImageSharp.Drawing/ImageSharp.Drawing.csproj index 30ca57b59..661f33e08 100644 --- a/src/ImageSharp.Drawing/ImageSharp.Drawing.csproj +++ b/src/ImageSharp.Drawing/ImageSharp.Drawing.csproj @@ -39,7 +39,8 @@ - + + All diff --git a/src/ImageSharp.Drawing/Primitives/ShapePath.cs b/src/ImageSharp.Drawing/Primitives/ShapePath.cs index 2a569f061..7a8c9e895 100644 --- a/src/ImageSharp.Drawing/Primitives/ShapePath.cs +++ b/src/ImageSharp.Drawing/Primitives/ShapePath.cs @@ -16,9 +16,8 @@ namespace SixLabors.ImageSharp.Primitives /// /// The shape. /// The pen to apply to the shape. - // TODO: SixLabors.shape will be moving to a Span/ReadOnlySpan based API shortly use ToArray for now. public ShapePath(IPath shape, IPen pen) - : base(shape.GenerateOutline(pen.StrokeWidth, pen.StrokePattern.ToArray())) + : base(shape.GenerateOutline(pen.StrokeWidth, pen.StrokePattern)) { } } diff --git a/src/ImageSharp.Drawing/Processing/Drawing/Processors/FillRegionProcessor.cs b/src/ImageSharp.Drawing/Processing/Drawing/Processors/FillRegionProcessor.cs index c81f4028b..1e968b97e 100644 --- a/src/ImageSharp.Drawing/Processing/Drawing/Processors/FillRegionProcessor.cs +++ b/src/ImageSharp.Drawing/Processing/Drawing/Processors/FillRegionProcessor.cs @@ -2,11 +2,11 @@ // Licensed under the Apache License, Version 2.0. using System; -using System.Runtime.CompilerServices; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Primitives; using SixLabors.ImageSharp.Processing.Drawing.Brushes; using SixLabors.ImageSharp.Processing.Processors; +using SixLabors.ImageSharp.Utils; using SixLabors.Memory; using SixLabors.Primitives; @@ -124,7 +124,7 @@ namespace SixLabors.ImageSharp.Processing.Drawing.Processors continue; } - QuickSort(buffer.Slice(0, pointsFound)); + QuickSort.Sort(buffer.Slice(0, pointsFound)); for (int point = 0; point < pointsFound; point += 2) { @@ -186,70 +186,5 @@ namespace SixLabors.ImageSharp.Processing.Drawing.Processors } } } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void Swap(ref float left, ref float right) - { - float tmp = left; - left = right; - right = tmp; - } - - private static void QuickSort(Span data) - { - if (data.Length < 2) - { - return; - } - else if (data.Length == 2) - { - if (data[0] > data[1]) - { - Swap(ref data[0], ref data[1]); - } - - return; - } - - QuickSort(ref data[0], 0, data.Length - 1); - } - - private static void QuickSort(ref float data0, int lo, int hi) - { - if (lo < hi) - { - int p = Partition(ref data0, lo, hi); - QuickSort(ref data0, lo, p); - QuickSort(ref data0, p + 1, hi); - } - } - - private static int Partition(ref float data0, int lo, int hi) - { - float pivot = Unsafe.Add(ref data0, lo); - int i = lo - 1; - int j = hi + 1; - while (true) - { - do - { - i = i + 1; - } - while (Unsafe.Add(ref data0, i) < pivot && i < hi); - - do - { - j = j - 1; - } - while (Unsafe.Add(ref data0, j) > pivot && j > lo); - - if (i >= j) - { - return j; - } - - Swap(ref Unsafe.Add(ref data0, i), ref Unsafe.Add(ref data0, j)); - } - } } } \ No newline at end of file diff --git a/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.Path.cs b/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.Path.cs deleted file mode 100644 index 9de73afcc..000000000 --- a/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.Path.cs +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright (c) Six Labors and contributors. -// Licensed under the Apache License, Version 2.0. - -using SixLabors.Fonts; -using SixLabors.ImageSharp.PixelFormats; -using SixLabors.ImageSharp.Processing.Drawing; -using SixLabors.ImageSharp.Processing.Drawing.Brushes; -using SixLabors.ImageSharp.Processing.Drawing.Pens; -using SixLabors.Shapes; - -namespace SixLabors.ImageSharp.Processing.Text -{ - /// - /// Adds extensions that allow the drawing of text along given paths to the type. - /// - public static partial class DrawTextExtensions - { - /// - /// Draws the text onto the the image filled via the brush. - /// - /// The type of the color. - /// The image this method extends. - /// The text. - /// The font. - /// The color. - /// The path. - /// - /// The . - /// - public static IImageProcessingContext DrawText(this IImageProcessingContext source, string text, Font font, TPixel color, IPath path) - where TPixel : struct, IPixel - => source.DrawText(TextGraphicsOptions.Default, text, font, color, path); - - /// - /// Draws the text onto the the image filled via the brush. - /// - /// The type of the color. - /// The image this method extends. - /// The options. - /// The text. - /// The font. - /// The color. - /// The path. - /// - /// The . - /// - public static IImageProcessingContext DrawText(this IImageProcessingContext source, TextGraphicsOptions options, string text, Font font, TPixel color, IPath path) - where TPixel : struct, IPixel - => source.DrawText(options, text, font, Brushes.Solid(color), null, path); - - /// - /// Draws the text onto the the image filled via the brush. - /// - /// The type of the color. - /// The image this method extends. - /// The text. - /// The font. - /// The brush. - /// The location. - /// - /// The . - /// - public static IImageProcessingContext DrawText(this IImageProcessingContext source, string text, Font font, IBrush brush, IPath path) - where TPixel : struct, IPixel - => source.DrawText(TextGraphicsOptions.Default, text, font, brush, path); - - /// - /// Draws the text onto the the image filled via the brush. - /// - /// The type of the color. - /// The image this method extends. - /// The options. - /// The text. - /// The font. - /// The brush. - /// The path. - /// - /// The . - /// - public static IImageProcessingContext DrawText(this IImageProcessingContext source, TextGraphicsOptions options, string text, Font font, IBrush brush, IPath path) - where TPixel : struct, IPixel - => source.DrawText(options, text, font, brush, null, path); - - /// - /// Draws the text onto the the image outlined via the pen. - /// - /// The type of the color. - /// The image this method extends. - /// The text. - /// The font. - /// The pen. - /// The path. - /// - /// The . - /// - public static IImageProcessingContext DrawText(this IImageProcessingContext source, string text, Font font, IPen pen, IPath path) - where TPixel : struct, IPixel - => source.DrawText(TextGraphicsOptions.Default, text, font, pen, path); - - /// - /// Draws the text onto the the image outlined via the pen. - /// - /// The type of the color. - /// The image this method extends. - /// The options. - /// The text. - /// The font. - /// The pen. - /// The path. - /// - /// The . - /// - public static IImageProcessingContext DrawText(this IImageProcessingContext source, TextGraphicsOptions options, string text, Font font, IPen pen, IPath path) - where TPixel : struct, IPixel - => source.DrawText(options, text, font, null, pen, path); - - /// - /// Draws the text onto the the image filled via the brush then outlined via the pen. - /// - /// The type of the color. - /// The image this method extends. - /// The text. - /// The font. - /// The brush. - /// The pen. - /// The path. - /// - /// The . - /// - public static IImageProcessingContext DrawText(this IImageProcessingContext source, string text, Font font, IBrush brush, IPen pen, IPath path) - where TPixel : struct, IPixel - => source.DrawText(TextGraphicsOptions.Default, text, font, brush, pen, path); - - /// - /// Draws the text onto the the image filled via the brush then outlined via the pen. - /// - /// The type of the color. - /// The image this method extends. - /// The options. - /// The text. - /// The font. - /// The brush. - /// The pen. - /// The path. - /// - /// The . - /// - public static IImageProcessingContext DrawText(this IImageProcessingContext source, TextGraphicsOptions options, string text, Font font, IBrush brush, IPen pen, IPath path) - where TPixel : struct, IPixel - { - float dpiX = DefaultTextDpi; - float dpiY = DefaultTextDpi; - - var style = new RendererOptions(font, dpiX, dpiY) - { - ApplyKerning = options.ApplyKerning, - TabWidth = options.TabWidth, - WrappingWidth = options.WrapTextWidth, - HorizontalAlignment = options.HorizontalAlignment, - VerticalAlignment = options.VerticalAlignment - }; - - IPathCollection glyphs = TextBuilder.GenerateGlyphs(text, path, style); - - var pathOptions = (GraphicsOptions)options; - if (brush != null) - { - source.Fill(pathOptions, brush, glyphs); - } - - if (pen != null) - { - source.Draw(pathOptions, pen, glyphs); - } - - return source; - } - } -} \ No newline at end of file diff --git a/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.cs b/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.cs index 8fede9693..a20d7f730 100644 --- a/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.cs +++ b/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.cs @@ -3,11 +3,10 @@ using SixLabors.Fonts; using SixLabors.ImageSharp.PixelFormats; -using SixLabors.ImageSharp.Processing.Drawing; using SixLabors.ImageSharp.Processing.Drawing.Brushes; using SixLabors.ImageSharp.Processing.Drawing.Pens; +using SixLabors.ImageSharp.Processing.Text.Processors; using SixLabors.Primitives; -using SixLabors.Shapes; namespace SixLabors.ImageSharp.Processing.Text { @@ -16,8 +15,6 @@ namespace SixLabors.ImageSharp.Processing.Text /// public static partial class DrawTextExtensions { - private static readonly int DefaultTextDpi = 72; - /// /// Draws the text onto the the image filled via the brush. /// @@ -150,33 +147,6 @@ namespace SixLabors.ImageSharp.Processing.Text /// public static IImageProcessingContext DrawText(this IImageProcessingContext source, TextGraphicsOptions options, string text, Font font, IBrush brush, IPen pen, PointF location) where TPixel : struct, IPixel - { - float dpiX = DefaultTextDpi; - float dpiY = DefaultTextDpi; - - var style = new RendererOptions(font, dpiX, dpiY, location) - { - ApplyKerning = options.ApplyKerning, - TabWidth = options.TabWidth, - WrappingWidth = options.WrapTextWidth, - HorizontalAlignment = options.HorizontalAlignment, - VerticalAlignment = options.VerticalAlignment - }; - - IPathCollection glyphs = TextBuilder.GenerateGlyphs(text, style); - - var pathOptions = (GraphicsOptions)options; - if (brush != null) - { - source.Fill(pathOptions, brush, glyphs); - } - - if (pen != null) - { - source.Draw(pathOptions, pen, glyphs); - } - - return source; - } + => source.ApplyProcessor(new DrawTextProcessor(options, text, font, brush, pen, location)); } } \ No newline at end of file diff --git a/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs new file mode 100644 index 000000000..9327f9449 --- /dev/null +++ b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs @@ -0,0 +1,471 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System; +using System.Collections.Generic; +using SixLabors.Fonts; +using SixLabors.ImageSharp.Advanced; +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Processing.Drawing.Brushes; +using SixLabors.ImageSharp.Processing.Drawing.Pens; +using SixLabors.ImageSharp.Processing.Processors; +using SixLabors.ImageSharp.Utils; +using SixLabors.Memory; +using SixLabors.Primitives; +using SixLabors.Shapes; + +namespace SixLabors.ImageSharp.Processing.Text.Processors +{ + /// + /// Using the brush as a source of pixels colors blends the brush color with source. + /// + /// The pixel format. + internal class DrawTextProcessor : ImageProcessor + where TPixel : struct, IPixel + { + private CachingGlyphRenderer textRenderer; + + /// + /// Initializes a new instance of the class. + /// + /// The options + /// The text we want to render + /// The font we want to render with + /// The brush to source pixel colors from. + /// The pen to outline text with. + /// The location on the image to start drawign the text from. + public DrawTextProcessor(TextGraphicsOptions options, string text, Font font, IBrush brush, IPen pen, PointF location) + { + Guard.NotNull(text, nameof(text)); + Guard.NotNull(font, nameof(font)); + if (brush == null && pen == null) + { + throw new ArgumentNullException($"at least one of {nameof(brush)} or {nameof(pen)} must not be null"); + } + + this.Options = options; + this.Text = text; + this.Font = font; + this.Location = location; + this.Brush = brush; + this.Pen = pen; + } + + /// + /// Gets the brush. + /// + public IBrush Brush { get; } + + /// + /// Gets the options + /// + public TextGraphicsOptions Options { get; } + + /// + /// Gets the text + /// + public string Text { get; } + + /// + /// Gets the pen used for outlining the text, if Null then we will not outline + /// + public IPen Pen { get; } + + /// + /// Gets the font used to render the text. + /// + public Font Font { get; } + + /// + /// Gets the location to draw the text at. + /// + public PointF Location { get; } + + protected override void BeforeImageApply(Image source, Rectangle sourceRectangle) + { + base.BeforeImageApply(source, sourceRectangle); + + // do everythign at the image level as we are deligating the processing down to other processors + var style = new RendererOptions(this.Font, this.Options.DpiX, this.Options.DpiY, this.Location) + { + ApplyKerning = this.Options.ApplyKerning, + TabWidth = this.Options.TabWidth, + WrappingWidth = this.Options.WrapTextWidth, + HorizontalAlignment = this.Options.HorizontalAlignment, + VerticalAlignment = this.Options.VerticalAlignment + }; + + this.textRenderer = new CachingGlyphRenderer(source.GetMemoryAllocator(), this.Text.Length, this.Pen, this.Brush != null); + this.textRenderer.Options = (GraphicsOptions)this.Options; + TextRenderer.RenderTextTo(this.textRenderer, this.Text, style); + } + + protected override void AfterImageApply(Image source, Rectangle sourceRectangle) + { + base.AfterImageApply(source, sourceRectangle); + this.textRenderer?.Dispose(); + this.textRenderer = null; + } + + /// + protected override void OnFrameApply(ImageFrame source, Rectangle sourceRectangle, Configuration configuration) + { + // this is a no-op as we have processes all as an image, we should be able to pass out of before email apply a skip frames outcome + Draw(this.textRenderer.FillOperations, this.Brush); + Draw(this.textRenderer.OutlineOperations, this.Pen?.StrokeFill); + + void Draw(List operations, IBrush brush) + { + if (operations?.Count > 0) + { + using (BrushApplicator app = brush.CreateApplicator(source, sourceRectangle, this.textRenderer.Options)) + { + foreach (DrawingOperation operation in operations) + { + Buffer2D buffer = operation.Map; + int startY = operation.Location.Y; + int startX = operation.Location.X; + int offSetSpan = 0; + if (startX < 0) + { + offSetSpan = -startX; + startX = 0; + } + + int fistRow = 0; + if (startY < 0) + { + fistRow = -startY; + } + + int end = operation.Map.Height; + + int maxHeight = source.Height - startY; + end = Math.Min(end, maxHeight); + + for (int row = fistRow; row < end; row++) + { + int y = startY + row; + Span span = buffer.GetRowSpan(row).Slice(offSetSpan); + app.Apply(span, startX, y); + } + } + } + } + } + } + + private struct DrawingOperation + { + public Buffer2D Map { get; set; } + + public Point Location { get; set; } + } + + private class CachingGlyphRenderer : IGlyphRenderer, IDisposable + { + private PathBuilder builder; + + private Point currentRenderPosition = default; + private GlyphRendererParameters currentGlyphRenderParams = default; + private int offset = 0; + private PointF currentPoint = default(PointF); + + private readonly Dictionary glyphData = new Dictionary(); + + private bool renderOutline = false; + private bool renderFill = false; + private bool raterizationRequired = false; + + public CachingGlyphRenderer(MemoryAllocator memoryAllocator, int size, IPen pen, bool renderFill) + { + this.MemoryAllocator = memoryAllocator; + this.Pen = pen; + this.renderFill = renderFill; + this.renderOutline = pen != null; + this.offset = 2; + if (this.renderFill) + { + this.FillOperations = new List(size); + } + + if (this.renderOutline) + { + this.offset = (int)MathF.Ceiling((pen.StrokeWidth * 2) + 2); + this.OutlineOperations = new List(size); + } + + this.builder = new PathBuilder(); + } + + public List FillOperations { get; } + + public List OutlineOperations { get; } + + public MemoryAllocator MemoryAllocator { get; internal set; } + + public IPen Pen { get; internal set; } + + public GraphicsOptions Options { get; internal set; } + + public void BeginFigure() + { + this.builder.StartFigure(); + } + + public bool BeginGlyph(RectangleF bounds, GlyphRendererParameters paramters) + { + this.currentRenderPosition = Point.Truncate(bounds.Location); + + // we have offset our rendering origion a little bit down to prevent edge cropping, move the draw origin up to compensate + this.currentRenderPosition = new Point(this.currentRenderPosition.X - this.offset, this.currentRenderPosition.Y - this.offset); + this.currentGlyphRenderParams = paramters; + if (this.glyphData.ContainsKey(paramters)) + { + // we have already drawn the glyph vectors skip trying again + this.raterizationRequired = false; + return false; + } + + // we check to see if we have a render cache and if we do then we render else + this.builder.Clear(); + + // ensure all glyphs render around [zero, zero] so offset negative root positions so when we draw the glyph we can offet it back + this.builder.SetOrigin(new PointF(-(int)bounds.X + this.offset, -(int)bounds.Y + this.offset)); + + this.raterizationRequired = true; + return true; + } + + public void BeginText(RectangleF bounds) + { + // not concerned about this one + this.OutlineOperations?.Clear(); + this.FillOperations?.Clear(); + } + + public void CubicBezierTo(PointF secondControlPoint, PointF thirdControlPoint, PointF point) + { + this.builder.AddBezier(this.currentPoint, secondControlPoint, thirdControlPoint, point); + this.currentPoint = point; + } + + public void Dispose() + { + foreach (KeyValuePair kv in this.glyphData) + { + kv.Value.Dispose(); + } + + this.glyphData.Clear(); + } + + public void EndFigure() + { + this.builder.CloseFigure(); + } + + public void EndGlyph() + { + GlyphRenderData renderData = default; + + // has the glyoh been rendedered already???? + if (this.raterizationRequired) + { + IPath path = this.builder.Build(); + + if (this.renderFill) + { + renderData.FillMap = this.Render(path); + } + + if (this.renderOutline) + { + if (this.Pen.StrokePattern.Length == 0) + { + path = path.GenerateOutline(this.Pen.StrokeWidth); + } + else + { + path = path.GenerateOutline(this.Pen.StrokeWidth, this.Pen.StrokePattern); + } + + renderData.OutlineMap = this.Render(path); + } + + this.glyphData[this.currentGlyphRenderParams] = renderData; + } + else + { + renderData = this.glyphData[this.currentGlyphRenderParams]; + } + + if (this.renderFill) + { + this.FillOperations.Add(new DrawingOperation + { + Location = this.currentRenderPosition, + Map = renderData.FillMap + }); + } + + if (this.renderOutline) + { + this.OutlineOperations.Add(new DrawingOperation + { + Location = this.currentRenderPosition, + Map = renderData.OutlineMap + }); + } + } + + private Buffer2D Render(IPath path) + { + Size size = Rectangle.Ceiling(path.Bounds).Size; + size = new Size(size.Width + (this.offset * 2), size.Height + (this.offset * 2)); + + float subpixelCount = 4; + float offset = 0.5f; + if (this.Options.Antialias) + { + offset = 0f; // we are antialising skip offsetting as real antalising should take care of offset. + subpixelCount = this.Options.AntialiasSubpixelDepth; + if (subpixelCount < 4) + { + subpixelCount = 4; + } + } + + // take the path inside the path builder, scan thing and generate a Buffer2d representing the glyph and cache it. + Buffer2D fullBuffer = this.MemoryAllocator.Allocate2D(size.Width + 1, size.Height + 1, true); + + using (IBuffer bufferBacking = this.MemoryAllocator.Allocate(path.MaxIntersections)) + using (IBuffer rowIntersectionBuffer = this.MemoryAllocator.Allocate(size.Width)) + { + float subpixelFraction = 1f / subpixelCount; + float subpixelFractionPoint = subpixelFraction / subpixelCount; + + for (int y = 0; y <= size.Height; y++) + { + Span scanline = fullBuffer.GetRowSpan(y); + bool scanlineDirty = false; + float yPlusOne = y + 1; + + for (float subPixel = (float)y; subPixel < yPlusOne; subPixel += subpixelFraction) + { + var start = new PointF(path.Bounds.Left - 1, subPixel); + var end = new PointF(path.Bounds.Right + 1, subPixel); + Span intersectionSpan = rowIntersectionBuffer.GetSpan(); + Span buffer = bufferBacking.GetSpan(); + int pointsFound = path.FindIntersections(start, end, intersectionSpan); + + if (pointsFound == 0) + { + // nothing on this line skip + continue; + } + + for (int i = 0; i < pointsFound && i < intersectionSpan.Length; i++) + { + buffer[i] = intersectionSpan[i].X; + } + + QuickSort.Sort(buffer.Slice(0, pointsFound)); + + for (int point = 0; point < pointsFound; point += 2) + { + // points will be paired up + float scanStart = buffer[point]; + float scanEnd = buffer[point + 1]; + int startX = (int)MathF.Floor(scanStart + offset); + int endX = (int)MathF.Floor(scanEnd + offset); + + if (startX >= 0 && startX < scanline.Length) + { + for (float x = scanStart; x < startX + 1; x += subpixelFraction) + { + scanline[startX] += subpixelFractionPoint; + scanlineDirty = true; + } + } + + if (endX >= 0 && endX < scanline.Length) + { + for (float x = endX; x < scanEnd; x += subpixelFraction) + { + scanline[endX] += subpixelFractionPoint; + scanlineDirty = true; + } + } + + int nextX = startX + 1; + endX = Math.Min(endX, scanline.Length); // reduce to end to the right edge + nextX = Math.Max(nextX, 0); + for (int x = nextX; x < endX; x++) + { + scanline[x] += subpixelFraction; + scanlineDirty = true; + } + } + } + + if (scanlineDirty) + { + if (!this.Options.Antialias) + { + for (int x = 0; x < size.Width; x++) + { + if (scanline[x] >= 0.5) + { + scanline[x] = 1; + } + else + { + scanline[x] = 0; + } + } + } + } + } + } + + return fullBuffer; + } + + public void EndText() + { + } + + public void LineTo(PointF point) + { + this.builder.AddLine(this.currentPoint, point); + this.currentPoint = point; + } + + public void MoveTo(PointF point) + { + this.builder.StartFigure(); + this.currentPoint = point; + } + + public void QuadraticBezierTo(PointF secondControlPoint, PointF point) + { + this.builder.AddBezier(this.currentPoint, secondControlPoint, point); + this.currentPoint = point; + } + + private struct GlyphRenderData : IDisposable + { + public Buffer2D FillMap; + + public Buffer2D OutlineMap; + + public void Dispose() + { + this.FillMap?.Dispose(); + this.OutlineMap?.Dispose(); + } + } + } + } +} \ No newline at end of file diff --git a/src/ImageSharp.Drawing/Processing/Text/TextGraphicsOptions.cs b/src/ImageSharp.Drawing/Processing/Text/TextGraphicsOptions.cs index bba473ddb..aaa6dea56 100644 --- a/src/ImageSharp.Drawing/Processing/Text/TextGraphicsOptions.cs +++ b/src/ImageSharp.Drawing/Processing/Text/TextGraphicsOptions.cs @@ -11,6 +11,8 @@ namespace SixLabors.ImageSharp.Processing.Text /// public struct TextGraphicsOptions { + private const int DefaultTextDpi = 72; + /// /// Represents the default . /// @@ -26,11 +28,16 @@ namespace SixLabors.ImageSharp.Processing.Text private float? tabWidth; + private float? dpiX; + + private float? dpiY; + private PixelBlenderMode blenderMode; private float wrapTextWidth; private HorizontalAlignment? horizontalAlignment; + private VerticalAlignment? verticalAlignment; /// @@ -49,6 +56,8 @@ namespace SixLabors.ImageSharp.Processing.Text this.blenderMode = PixelBlenderMode.Normal; this.blendPercentage = 1; this.antialias = enableAntialiasing; + this.dpiX = DefaultTextDpi; + this.dpiY = DefaultTextDpi; } /// @@ -90,6 +99,16 @@ namespace SixLabors.ImageSharp.Processing.Text /// public float WrapTextWidth { get => this.wrapTextWidth; set => this.wrapTextWidth = value; } + /// + /// Gets or sets a value indicating the DPI to render text along the X axis. + /// + public float DpiX { get => this.dpiX ?? DefaultTextDpi; set => this.dpiX = value; } + + /// + /// Gets or sets a value indicating the DPI to render text along the Y axis. + /// + public float DpiY { get => this.dpiY ?? DefaultTextDpi; set => this.dpiY = value; } + /// /// Gets or sets a value indicating how to align the text relative to the rendering space. /// If is greater than zero it will align relative to the space diff --git a/src/ImageSharp.Drawing/Utils/QuickSort.cs b/src/ImageSharp.Drawing/Utils/QuickSort.cs new file mode 100644 index 000000000..ca1da5505 --- /dev/null +++ b/src/ImageSharp.Drawing/Utils/QuickSort.cs @@ -0,0 +1,84 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System; +using System.Runtime.CompilerServices; + +namespace SixLabors.ImageSharp.Utils +{ + /// + /// Optimized quick sort implementation for Span{float} input + /// + internal class QuickSort + { + /// + /// Sorts the elements of in ascending order + /// + /// The items to sort + public static void Sort(Span data) + { + if (data.Length < 2) + { + return; + } + + if (data.Length == 2) + { + if (data[0] > data[1]) + { + Swap(ref data[0], ref data[1]); + } + + return; + } + + Sort(ref data[0], 0, data.Length - 1); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Swap(ref float left, ref float right) + { + float tmp = left; + left = right; + right = tmp; + } + + private static void Sort(ref float data0, int lo, int hi) + { + if (lo < hi) + { + int p = Partition(ref data0, lo, hi); + Sort(ref data0, lo, p); + Sort(ref data0, p + 1, hi); + } + } + + private static int Partition(ref float data0, int lo, int hi) + { + float pivot = Unsafe.Add(ref data0, lo); + int i = lo - 1; + int j = hi + 1; + while (true) + { + do + { + i = i + 1; + } + while (Unsafe.Add(ref data0, i) < pivot && i < hi); + + do + { + j = j - 1; + } + while (Unsafe.Add(ref data0, j) > pivot && j > lo); + + if (i >= j) + { + return j; + } + + Swap(ref Unsafe.Add(ref data0, i), ref Unsafe.Add(ref data0, j)); + } + } + } +} diff --git a/tests/ImageSharp.Benchmarks/Drawing/DrawText.cs b/tests/ImageSharp.Benchmarks/Drawing/DrawText.cs new file mode 100644 index 000000000..96912a6df --- /dev/null +++ b/tests/ImageSharp.Benchmarks/Drawing/DrawText.cs @@ -0,0 +1,101 @@ +// +// Copyright (c) James Jackson-South and contributors. +// Licensed under the Apache License, Version 2.0. +// + +using System.Drawing; +using System.Drawing.Drawing2D; +using BenchmarkDotNet.Attributes; +using System.IO; +using System.Numerics; + +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Processing; +using SixLabors.ImageSharp.Processing.Text; +using SixLabors.ImageSharp.Processing.Overlays; +using SixLabors.ImageSharp.Processing.Drawing; +using System.Linq; + +namespace SixLabors.ImageSharp.Benchmarks +{ + + [MemoryDiagnoser] + public class DrawText : BenchmarkBase + { + + [Params(10, 100)] + public int TextIterations{ get; set; } + public string TextPhrase { get; set; } = "Hello World"; + public string TextToRender => string.Join(" ", Enumerable.Repeat(TextPhrase, TextIterations)); + + + [Benchmark(Baseline = true, Description = "System.Drawing Draw Text")] + public void DrawTextSystemDrawing() + { + using (Bitmap destination = new Bitmap(800, 800)) + { + + using (Graphics graphics = Graphics.FromImage(destination)) + { + graphics.InterpolationMode = InterpolationMode.Default; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + Pen pen = new Pen(System.Drawing.Color.HotPink, 10); + var font = new Font("Arial", 12, GraphicsUnit.Point); + graphics.DrawString(TextToRender, font, Brushes.HotPink, new RectangleF(10, 10, 780, 780)); + } + } + } + + + [Benchmark(Description = "ImageSharp Draw Text - Cached Glyphs")] + public void DrawTextCore() + { + using (Image image = new Image(800, 800)) + { + var font = SixLabors.Fonts.SystemFonts.CreateFont("Arial", 12); + image.Mutate(x => x.ApplyProcessor(new SixLabors.ImageSharp.Processing.Text.Processors.DrawTextProcessor(new TextGraphicsOptions(true) { WrapTextWidth = 780 }, TextToRender, font, SixLabors.ImageSharp.Processing.Drawing.Brushes.Brushes.Solid(Rgba32.HotPink), null, new SixLabors.Primitives.PointF(10, 10)))); + } + } + + [Benchmark(Description = "ImageSharp Draw Text - Nieve")] + public void DrawTextCoreOld() + { + using (Image image = new Image(800, 800)) + { + var font = SixLabors.Fonts.SystemFonts.CreateFont("Arial", 12); + image.Mutate(x => DrawTextOldVersion(x, new TextGraphicsOptions(true) { WrapTextWidth = 780 }, TextToRender, font, SixLabors.ImageSharp.Processing.Drawing.Brushes.Brushes.Solid(Rgba32.HotPink), null, new SixLabors.Primitives.PointF(10, 10))); + } + + IImageProcessingContext DrawTextOldVersion(IImageProcessingContext source, TextGraphicsOptions options, string text, SixLabors.Fonts.Font font, SixLabors.ImageSharp.Processing.Drawing.Brushes.IBrush brush, SixLabors.ImageSharp.Processing.Drawing.Pens.IPen pen, SixLabors.Primitives.PointF location) + where TPixel : struct, IPixel + { + float dpiX = 72; + float dpiY = 72; + + var style = new SixLabors.Fonts.RendererOptions(font, dpiX, dpiY, location) + { + ApplyKerning = options.ApplyKerning, + TabWidth = options.TabWidth, + WrappingWidth = options.WrapTextWidth, + HorizontalAlignment = options.HorizontalAlignment, + VerticalAlignment = options.VerticalAlignment + }; + + Shapes.IPathCollection glyphs = Shapes.TextBuilder.GenerateGlyphs(text, style); + + var pathOptions = (GraphicsOptions)options; + if (brush != null) + { + source.Fill(pathOptions, brush, glyphs); + } + + if (pen != null) + { + source.Draw(pathOptions, pen, glyphs); + } + + return source; + } + } + } +} \ No newline at end of file diff --git a/tests/ImageSharp.Benchmarks/Drawing/DrawTextOutline.cs b/tests/ImageSharp.Benchmarks/Drawing/DrawTextOutline.cs new file mode 100644 index 000000000..e85e33235 --- /dev/null +++ b/tests/ImageSharp.Benchmarks/Drawing/DrawTextOutline.cs @@ -0,0 +1,99 @@ +// +// Copyright (c) James Jackson-South and contributors. +// Licensed under the Apache License, Version 2.0. +// + +using System.Drawing; +using System.Drawing.Drawing2D; +using BenchmarkDotNet.Attributes; +using System.IO; +using System.Numerics; + +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Processing; +using SixLabors.ImageSharp.Processing.Text; +using SixLabors.ImageSharp.Processing.Overlays; +using SixLabors.ImageSharp.Processing.Drawing; +using System.Linq; + +namespace SixLabors.ImageSharp.Benchmarks +{ + + [MemoryDiagnoser] + public class DrawTextOutline : BenchmarkBase + { + + [Params(10, 100)] + public int TextIterations{ get; set; } + public string TextPhrase { get; set; } = "Hello World"; + public string TextToRender => string.Join(" ", Enumerable.Repeat(TextPhrase, TextIterations)); + + + [Benchmark(Baseline = true, Description = "System.Drawing Draw Text Outline")] + public void DrawTextSystemDrawing() + { + using (Bitmap destination = new Bitmap(800, 800)) + { + + using (Graphics graphics = Graphics.FromImage(destination)) + { + graphics.InterpolationMode = InterpolationMode.Default; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + Pen pen = new Pen(System.Drawing.Color.HotPink, 10); + var font = new Font("Arial", 12, GraphicsUnit.Point); + var gp = new GraphicsPath(); + gp.AddString(TextToRender, font.FontFamily, (int)font.Style, font.Size, new RectangleF(10, 10, 780, 780), new StringFormat()); + graphics.DrawPath(pen, gp); + } + } + } + + [Benchmark(Description = "ImageSharp Draw Text Outline - Cached Glyphs")] + public void DrawTextCore() + { + using (Image image = new Image(800, 800)) + { + var font = SixLabors.Fonts.SystemFonts.CreateFont("Arial", 12); + image.Mutate(x => x.ApplyProcessor(new SixLabors.ImageSharp.Processing.Text.Processors.DrawTextProcessor(new TextGraphicsOptions(true) { WrapTextWidth = 780 }, TextToRender, font, null, SixLabors.ImageSharp.Processing.Drawing.Pens.Pens.Solid(Rgba32.HotPink, 10), new SixLabors.Primitives.PointF(10, 10)))); + } + } + + [Benchmark(Description = "ImageSharp Draw Text Outline - Nieve")] + public void DrawTextCoreOld() + { + using (Image image = new Image(800, 800)) + { + var font = SixLabors.Fonts.SystemFonts.CreateFont("Arial", 12); + image.Mutate(x => DrawTextOldVersion(x, new TextGraphicsOptions(true) { WrapTextWidth = 780 }, TextToRender, font, null, SixLabors.ImageSharp.Processing.Drawing.Pens.Pens.Solid(Rgba32.HotPink, 10), new SixLabors.Primitives.PointF(10, 10))); + } + + IImageProcessingContext DrawTextOldVersion(IImageProcessingContext source, TextGraphicsOptions options, string text, SixLabors.Fonts.Font font, SixLabors.ImageSharp.Processing.Drawing.Brushes.IBrush brush, SixLabors.ImageSharp.Processing.Drawing.Pens.IPen pen, SixLabors.Primitives.PointF location) + where TPixel : struct, IPixel + { + var style = new SixLabors.Fonts.RendererOptions(font, options.DpiX, options.DpiY, location) + { + ApplyKerning = options.ApplyKerning, + TabWidth = options.TabWidth, + WrappingWidth = options.WrapTextWidth, + HorizontalAlignment = options.HorizontalAlignment, + VerticalAlignment = options.VerticalAlignment + }; + + Shapes.IPathCollection glyphs = Shapes.TextBuilder.GenerateGlyphs(text, style); + + var pathOptions = (GraphicsOptions)options; + if (brush != null) + { + source.Fill(pathOptions, brush, glyphs); + } + + if (pen != null) + { + source.Draw(pathOptions, pen, glyphs); + } + + return source; + } + } + } +} \ No newline at end of file diff --git a/tests/ImageSharp.Benchmarks/ImageSharp.Benchmarks.csproj b/tests/ImageSharp.Benchmarks/ImageSharp.Benchmarks.csproj index 9a58f350a..67faa7213 100644 --- a/tests/ImageSharp.Benchmarks/ImageSharp.Benchmarks.csproj +++ b/tests/ImageSharp.Benchmarks/ImageSharp.Benchmarks.csproj @@ -18,6 +18,7 @@ + diff --git a/tests/ImageSharp.Tests/Drawing/BeziersTests.cs b/tests/ImageSharp.Tests/Drawing/BeziersTests.cs index 6dc2fae89..a5fda7958 100644 --- a/tests/ImageSharp.Tests/Drawing/BeziersTests.cs +++ b/tests/ImageSharp.Tests/Drawing/BeziersTests.cs @@ -7,12 +7,11 @@ using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; using SixLabors.ImageSharp.Processing.Drawing; using SixLabors.ImageSharp.Processing.Overlays; +using SixLabors.Memory; using Xunit; namespace SixLabors.ImageSharp.Tests.Drawing { - using SixLabors.Memory; - public class Beziers : FileTestBase { [Fact] diff --git a/tests/ImageSharp.Tests/Drawing/Paths/DrawPathCollection.cs b/tests/ImageSharp.Tests/Drawing/Paths/DrawPathCollection.cs new file mode 100644 index 000000000..ecdfd03e5 --- /dev/null +++ b/tests/ImageSharp.Tests/Drawing/Paths/DrawPathCollection.cs @@ -0,0 +1,117 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System.Numerics; +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Primitives; +using SixLabors.ImageSharp.Processing.Drawing; +using SixLabors.ImageSharp.Processing.Drawing.Brushes; +using SixLabors.ImageSharp.Processing.Drawing.Pens; +using SixLabors.ImageSharp.Processing.Drawing.Processors; +using SixLabors.Shapes; +using Xunit; + +namespace SixLabors.ImageSharp.Tests.Drawing.Paths +{ + public class DrawPathCollection : BaseImageOperationsExtensionTest + { + GraphicsOptions noneDefault = new GraphicsOptions(); + Rgba32 color = Rgba32.HotPink; + Pen pen = Pens.Solid(Rgba32.HotPink, 1); + IPath path1 = new Path(new LinearLineSegment(new SixLabors.Primitives.PointF[] { + new Vector2(10,10), + new Vector2(20,10), + new Vector2(20,10), + new Vector2(30,10), + })); + IPath path2 = new Path(new LinearLineSegment(new SixLabors.Primitives.PointF[] { + new Vector2(10,10), + new Vector2(20,10), + new Vector2(20,10), + new Vector2(30,10), + })); + + IPathCollection pathCollection; + + public DrawPathCollection() + { + this.pathCollection = new PathCollection(this.path1, this.path2); + } + + [Fact] + public void CorrectlySetsBrushAndPath() + { + this.operations.Draw(this.pen, this.pathCollection); + + for (int i = 0; i < 2; i++) + { + FillRegionProcessor processor = this.Verify>(i); + + Assert.Equal(GraphicsOptions.Default, processor.Options); + + ShapePath region = Assert.IsType(processor.Region); + + // path is converted to a polygon before filling + ComplexPolygon polygon = Assert.IsType(region.Shape); + + Assert.Equal(this.pen.StrokeFill, processor.Brush); + } + } + + [Fact] + public void CorrectlySetsBrushPathOptions() + { + this.operations.Draw(this.noneDefault, this.pen, this.pathCollection); + + for (int i = 0; i < 2; i++) + { + FillRegionProcessor processor = this.Verify>(i); + + Assert.Equal(this.noneDefault, processor.Options); + + ShapePath region = Assert.IsType(processor.Region); + ComplexPolygon polygon = Assert.IsType(region.Shape); + + Assert.Equal(this.pen.StrokeFill, processor.Brush); + } + } + + [Fact] + public void CorrectlySetsColorAndPath() + { + this.operations.Draw(this.color, 1, this.pathCollection); + + for (int i = 0; i < 2; i++) + { + FillRegionProcessor processor = this.Verify>(i); + + Assert.Equal(GraphicsOptions.Default, processor.Options); + + ShapePath region = Assert.IsType(processor.Region); + ComplexPolygon polygon = Assert.IsType(region.Shape); + + SolidBrush brush = Assert.IsType>(processor.Brush); + Assert.Equal(this.color, brush.Color); + } + } + + [Fact] + public void CorrectlySetsColorPathAndOptions() + { + this.operations.Draw(this.noneDefault, this.color, 1, this.pathCollection); + + for (int i = 0; i < 2; i++) + { + FillRegionProcessor processor = this.Verify>(i); + + Assert.Equal(this.noneDefault, processor.Options); + + ShapePath region = Assert.IsType(processor.Region); + ComplexPolygon polygon = Assert.IsType(region.Shape); + + SolidBrush brush = Assert.IsType>(processor.Brush); + Assert.Equal(this.color, brush.Color); + } + } + } +} diff --git a/tests/ImageSharp.Tests/Drawing/Text/DrawText.Path.cs b/tests/ImageSharp.Tests/Drawing/Text/DrawText.Path.cs deleted file mode 100644 index 4649bee6b..000000000 --- a/tests/ImageSharp.Tests/Drawing/Text/DrawText.Path.cs +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright (c) Six Labors and contributors. -// Licensed under the Apache License, Version 2.0. - -using System.Numerics; -using SixLabors.Fonts; -using SixLabors.ImageSharp.PixelFormats; -using SixLabors.ImageSharp.Processing.Drawing.Brushes; -using SixLabors.ImageSharp.Processing.Drawing.Pens; -using SixLabors.ImageSharp.Processing.Drawing.Processors; -using SixLabors.ImageSharp.Processing.Text; -using SixLabors.Shapes; -using Xunit; - -namespace SixLabors.ImageSharp.Tests.Drawing.Text -{ - public class DrawText_Path : BaseImageOperationsExtensionTest - { - Rgba32 color = Rgba32.HotPink; - - SolidBrush brush = Brushes.Solid(Rgba32.HotPink); - - IPath path = new SixLabors.Shapes.Path( - new LinearLineSegment( - new SixLabors.Primitives.PointF[] { new Vector2(10, 10), new Vector2(20, 10), new Vector2(20, 10), new Vector2(30, 10), })); - - private readonly FontCollection FontCollection; - - private readonly Font Font; - - public DrawText_Path() - { - this.FontCollection = new FontCollection(); - this.Font = this.FontCollection.Install(TestFontUtilities.GetPath("SixLaborsSampleAB.woff")).CreateFont(12); - } - - [Fact] - public void FillsForEachACharachterWhenBrushSetAndNotPen() - { - this.operations.DrawText( - new TextGraphicsOptions(true), - "123", - this.Font, - Brushes.Solid(Rgba32.Red), - null, - this.path); - - this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - } - - [Fact] - public void FillsForEachACharachterWhenBrushSetAndNotPenDefaultOptions() - { - this.operations.DrawText("123", this.Font, Brushes.Solid(Rgba32.Red), null, this.path); - - this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - } - - [Fact] - public void FillsForEachACharachterWhenBrushSet() - { - this.operations.DrawText(new TextGraphicsOptions(true), "123", this.Font, Brushes.Solid(Rgba32.Red), this.path); - - this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - } - - [Fact] - public void FillsForEachACharachterWhenBrushSetDefaultOptions() - { - this.operations.DrawText("123", this.Font, Brushes.Solid(Rgba32.Red), this.path); - - this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - } - - [Fact] - public void FillsForEachACharachterWhenColorSet() - { - this.operations.DrawText(new TextGraphicsOptions(true), "123", this.Font, Rgba32.Red, this.path); - - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - - SolidBrush brush = Assert.IsType>(processor.Brush); - Assert.Equal(Rgba32.Red, brush.Color); - } - - [Fact] - public void FillsForEachACharachterWhenColorSetDefaultOptions() - { - this.operations.DrawText("123", this.Font, Rgba32.Red, this.path); - - FillRegionProcessor processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - - SolidBrush brush = Assert.IsType>(processor.Brush); - Assert.Equal(Rgba32.Red, brush.Color); - } - - [Fact] - public void DrawForEachACharachterWhenPenSetAndNotBrush() - { - this.operations.DrawText( - new TextGraphicsOptions(true), - "123", - this.Font, - null, - Pens.Dash(Rgba32.Red, 1), - this.path); - - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - } - - [Fact] - public void DrawForEachACharachterWhenPenSetAndNotBrushDefaultOptions() - { - this.operations.DrawText("123", this.Font, null, Pens.Dash(Rgba32.Red, 1), this.path); - - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - } - - [Fact] - public void DrawForEachACharachterWhenPenSet() - { - this.operations.DrawText(new TextGraphicsOptions(true), "123", this.Font, Pens.Dash(Rgba32.Red, 1), this.path); - - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - } - - [Fact] - public void DrawForEachACharachterWhenPenSetDefaultOptions() - { - this.operations.DrawText("123", this.Font, Pens.Dash(Rgba32.Red, 1), this.path); - - FillRegionProcessor processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - } - - [Fact] - public void DrawForEachACharachterWhenPenSetAndFillFroEachWhenBrushSet() - { - this.operations.DrawText( - new TextGraphicsOptions(true), - "123", - this.Font, - Brushes.Solid(Rgba32.Red), - Pens.Dash(Rgba32.Red, 1), - this.path); - - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - this.Verify>(3); - this.Verify>(4); - this.Verify>(5); - } - - [Fact] - public void DrawForEachACharachterWhenPenSetAndFillFroEachWhenBrushSetDefaultOptions() - { - this.operations.DrawText("123", this.Font, Brushes.Solid(Rgba32.Red), Pens.Dash(Rgba32.Red, 1), this.path); - - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - this.Verify>(3); - this.Verify>(4); - this.Verify>(5); - } - - [Fact] - public void BrushAppliesBeforPen() - { - this.operations.DrawText( - new TextGraphicsOptions(true), - "1", - this.Font, - Brushes.Solid(Rgba32.Red), - Pens.Dash(Rgba32.Red, 1), - this.path); - - var processor = this.Verify>(0); - this.Verify>(1); - } - - [Fact] - public void BrushAppliesBeforPenDefaultOptions() - { - this.operations.DrawText("1", this.Font, Brushes.Solid(Rgba32.Red), Pens.Dash(Rgba32.Red, 1), this.path); - - var processor = this.Verify>(0); - this.Verify>(1); - } - } -} diff --git a/tests/ImageSharp.Tests/Drawing/Text/DrawText.cs b/tests/ImageSharp.Tests/Drawing/Text/DrawText.cs index 88b650a3e..2a03eb415 100644 --- a/tests/ImageSharp.Tests/Drawing/Text/DrawText.cs +++ b/tests/ImageSharp.Tests/Drawing/Text/DrawText.cs @@ -8,6 +8,8 @@ using SixLabors.ImageSharp.Processing.Drawing.Brushes; using SixLabors.ImageSharp.Processing.Drawing.Pens; using SixLabors.ImageSharp.Processing.Drawing.Processors; using SixLabors.ImageSharp.Processing.Text; +using SixLabors.ImageSharp.Processing.Text.Processors; +using SixLabors.Primitives; using SixLabors.Shapes; using Xunit; @@ -44,9 +46,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text null, Vector2.Zero); - this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + this.Verify>(0); } [Fact] @@ -54,9 +54,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { this.operations.DrawText("123", this.Font, Brushes.Solid(Rgba32.Red), null, Vector2.Zero); - this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + this.Verify>(0); } [Fact] @@ -64,9 +62,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { this.operations.DrawText(new TextGraphicsOptions(true), "123", this.Font, Brushes.Solid(Rgba32.Red), Vector2.Zero); - this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + this.Verify>(0); } [Fact] @@ -74,9 +70,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { this.operations.DrawText("123", this.Font, Brushes.Solid(Rgba32.Red), Vector2.Zero); - this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + this.Verify>(0); } [Fact] @@ -84,9 +78,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { this.operations.DrawText(new TextGraphicsOptions(true), "123", this.Font, Rgba32.Red, Vector2.Zero); - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + var processor = this.Verify>(0); SolidBrush brush = Assert.IsType>(processor.Brush); Assert.Equal(Rgba32.Red, brush.Color); @@ -97,9 +89,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { this.operations.DrawText("123", this.Font, Rgba32.Red, Vector2.Zero); - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + var processor = this.Verify>(0); SolidBrush brush = Assert.IsType>(processor.Brush); Assert.Equal(Rgba32.Red, brush.Color); @@ -116,9 +106,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text Pens.Dash(Rgba32.Red, 1), Vector2.Zero); - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + var processor = this.Verify>(0); } [Fact] @@ -126,9 +114,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { this.operations.DrawText("123", this.Font, null, Pens.Dash(Rgba32.Red, 1), Vector2.Zero); - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + var processor = this.Verify>(0); } [Fact] @@ -136,9 +122,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { this.operations.DrawText(new TextGraphicsOptions(true), "123", this.Font, Pens.Dash(Rgba32.Red, 1), Vector2.Zero); - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + var processor = this.Verify>(0); } [Fact] @@ -146,9 +130,14 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { this.operations.DrawText("123", this.Font, Pens.Dash(Rgba32.Red, 1), Vector2.Zero); - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + var processor = this.Verify>(0); + + Assert.Equal("123", processor.Text); + Assert.Equal(this.Font, processor.Font); + var penBrush = Assert.IsType>(processor.Pen.StrokeFill); + Assert.Equal(Rgba32.Red, penBrush.Color); + Assert.Equal(1, processor.Pen.StrokeWidth); + Assert.Equal(PointF.Empty, processor.Location); } [Fact] @@ -162,50 +151,16 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text Pens.Dash(Rgba32.Red, 1), Vector2.Zero); - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - - this.Verify>(3); - this.Verify>(4); - this.Verify>(5); - } - - [Fact] - public void DrawForEachACharachterWhenPenSetAndFillFroEachWhenBrushSetDefaultOptions() - { - this.operations.DrawText("123", this.Font, Brushes.Solid(Rgba32.Red), Pens.Dash(Rgba32.Red, 1), Vector2.Zero); - - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); - this.Verify>(3); - this.Verify>(4); - this.Verify>(5); - } - - [Fact] - public void BrushAppliesBeforePen() - { - this.operations.DrawText( - new TextGraphicsOptions(true), - "1", - this.Font, - Brushes.Solid(Rgba32.Red), - Pens.Dash(Rgba32.Red, 1), - Vector2.Zero); - - var processor = this.Verify>(0); - this.Verify>(1); - } + var processor = this.Verify>(0); - [Fact] - public void BrushAppliesBeforPenDefaultOptions() - { - this.operations.DrawText("1", this.Font, Brushes.Solid(Rgba32.Red), Pens.Dash(Rgba32.Red, 1), Vector2.Zero); - - var processor = this.Verify>(0); - this.Verify>(1); + Assert.Equal("123", processor.Text); + Assert.Equal(this.Font, processor.Font); + var brush = Assert.IsType>(processor.Brush); + Assert.Equal(Rgba32.Red, brush.Color); + Assert.Equal(PointF.Empty, processor.Location); + var penBrush = Assert.IsType>(processor.Pen.StrokeFill); + Assert.Equal(Rgba32.Red, penBrush.Color); + Assert.Equal(1, processor.Pen.StrokeWidth); } } } diff --git a/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs b/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs index a9c7a6ebb..3ceba0838 100644 --- a/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs +++ b/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs @@ -17,8 +17,12 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text using System; using System.Linq; using System.Text; - + using SixLabors.ImageSharp.Processing.Drawing.Brushes; + using SixLabors.ImageSharp.Processing.Drawing.Brushes.GradientBrushes; + using SixLabors.ImageSharp.Processing.Drawing.Pens; + using SixLabors.ImageSharp.Tests.TestUtilities.ImageComparison; using SixLabors.Primitives; + using SixLabors.Shapes; [GroupOutput("Drawing/Text")] public class DrawTextOnImageTests @@ -27,9 +31,9 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text private const string TestText = "Sphinx of black quartz, judge my vow\n0123456789"; - private const string TestText2 = - "THISISTESTWORDS "; - + public static ImageComparer TextDrawingComparer = ImageComparer.TolerantPercentage(0.01f); + public static ImageComparer OutlinedTextDrawingComparer = ImageComparer.TolerantPercentage(0.5f, 3); + [Theory] [WithSolidFilledImages(200, 100, "White", PixelTypes.Rgba32, 50, 0, 0, "SixLaborsSampleAB.woff", AB)] [WithSolidFilledImages(900, 100, "White", PixelTypes.Rgba32, 50, 0, 0, "OpenSans-Regular.ttf", TestText)] @@ -45,16 +49,15 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text where TPixel : struct, IPixel { Font font = CreateFont(fontName, fontSize); - string fnDisplayText = text.Replace("\n", ""); - fnDisplayText = fnDisplayText.Substring(0, Math.Min(fnDisplayText.Length, 4)); TPixel color = NamedColors.Black; provider.VerifyOperation( + TextDrawingComparer, img => - { - img.Mutate(c => c.DrawText(text, new Font(font, fontSize), color, new PointF(x, y))); - }, - $"{fontName}-{fontSize}-{fnDisplayText}-({x},{y})", + { + img.Mutate(c => c.DrawText(text, new Font(font, fontSize), color, new PointF(x, y))); + }, + $"{fontName}-{fontSize}-{ToTestOutputDisplayText(text)}-({x},{y})", appendPixelTypeToFileName: false, appendSourceFileOrDescription: true); } @@ -84,15 +87,16 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text } var textOptions = new TextGraphicsOptions - { - Antialias = true, - ApplyKerning = true, - VerticalAlignment = VerticalAlignment.Top, - HorizontalAlignment = HorizontalAlignment.Left, - }; + { + Antialias = true, + ApplyKerning = true, + VerticalAlignment = VerticalAlignment.Top, + HorizontalAlignment = HorizontalAlignment.Left, + }; TPixel color = NamedColors.Black; provider.VerifyOperation( + TextDrawingComparer, img => { img.Mutate(c => c.DrawText(textOptions, sb.ToString(), font, color, new PointF(10, 5))); @@ -101,8 +105,69 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text false); } + [Theory] + [WithSolidFilledImages(200, 100, "White", PixelTypes.Rgba32, 50, 0, 0, "SixLaborsSampleAB.woff", AB)] + [WithSolidFilledImages(900, 100, "White", PixelTypes.Rgba32, 50, 0, 0, "OpenSans-Regular.ttf", TestText)] + [WithSolidFilledImages(1100, 200, "White", PixelTypes.Rgba32, 50, 150, 100, "OpenSans-Regular.ttf", TestText)] + public void FontShapesAreRenderedCorrectlyWithAPen( + TestImageProvider provider, + int fontSize, + int x, + int y, + string fontName, + string text) + where TPixel : struct, IPixel + { + Font font = CreateFont(fontName, fontSize); + TPixel color = NamedColors.Black; + + provider.VerifyOperation( + OutlinedTextDrawingComparer, + img => + { + img.Mutate(c => c.DrawText(text, new Font(font, fontSize), null, Pens.Solid(color, 1), new PointF(x, y))); + }, + $"pen_{fontName}-{fontSize}-{ToTestOutputDisplayText(text)}-({x},{y})", + appendPixelTypeToFileName: false, + appendSourceFileOrDescription: true); + } + + [Theory] + [WithSolidFilledImages(200, 100, "White", PixelTypes.Rgba32, 50, 0, 0, "SixLaborsSampleAB.woff", AB)] + [WithSolidFilledImages(900, 100, "White", PixelTypes.Rgba32, 50, 0, 0, "OpenSans-Regular.ttf", TestText)] + [WithSolidFilledImages(1100, 200, "White", PixelTypes.Rgba32, 50, 150, 100, "OpenSans-Regular.ttf", TestText)] + public void FontShapesAreRenderedCorrectlyWithAPenPatterned( + TestImageProvider provider, + int fontSize, + int x, + int y, + string fontName, + string text) + where TPixel : struct, IPixel + { + Font font = CreateFont(fontName, fontSize); + TPixel color = NamedColors.Black; + + provider.VerifyOperation( + OutlinedTextDrawingComparer, + img => + { + img.Mutate(c => c.DrawText(text, new Font(font, fontSize), null, Pens.DashDot(color, 3), new PointF(x, y))); + }, + $"pen_{fontName}-{fontSize}-{ToTestOutputDisplayText(text)}-({x},{y})", + appendPixelTypeToFileName: false, + appendSourceFileOrDescription: true); + } + 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", ""); + fnDisplayText = fnDisplayText.Substring(0, Math.Min(fnDisplayText.Length, 4)); + return fnDisplayText; + } + private static Font CreateFont(string fontName, int size) { var fontCollection = new FontCollection(); diff --git a/tests/ImageSharp.Tests/Drawing/Utils/QuickSortTests.cs b/tests/ImageSharp.Tests/Drawing/Utils/QuickSortTests.cs new file mode 100644 index 000000000..6660cd87a --- /dev/null +++ b/tests/ImageSharp.Tests/Drawing/Utils/QuickSortTests.cs @@ -0,0 +1,51 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +namespace SixLabors.ImageSharp.Tests.Drawing.Utils +{ + using System; + using System.Linq; + + using SixLabors.ImageSharp.Utils; + + using Xunit; + + public class QuickSortTests + { + public static readonly TheoryData Data = new TheoryData() + { + new float[]{ 3, 2, 1 }, + new float[0], + new float[] { 42}, + new float[] { 1, 2}, + new float[] { 2, 1}, + new float[] { 5, 1, 2, 3, 0} + }; + + [Theory] + [MemberData(nameof(Data))] + public void Sort(float[] data) + { + float[] expected = data.ToArray(); + + Array.Sort(expected); + + QuickSort.Sort(data); + + Assert.Equal(expected, data); + } + + [Fact] + public void SortSlice() + { + float[] data = { 3, 2, 1, 0, -1 }; + + Span slice = data.AsSpan(1, 3); + QuickSort.Sort(slice); + float[] actual = slice.ToArray(); + float[] expected = { 0, 1, 2 }; + + Assert.Equal(actual, expected); + } + } +} \ No newline at end of file diff --git a/tests/ImageSharp.Tests/ImageSharp.Tests.csproj b/tests/ImageSharp.Tests/ImageSharp.Tests.csproj index 139df3972..fa165de5f 100644 --- a/tests/ImageSharp.Tests/ImageSharp.Tests.csproj +++ b/tests/ImageSharp.Tests/ImageSharp.Tests.csproj @@ -45,6 +45,12 @@ + + PreserveNewest + + + PreserveNewest + PreserveNewest diff --git a/tests/Images/External b/tests/Images/External index 802ffbae9..0e6407be7 160000 --- a/tests/Images/External +++ b/tests/Images/External @@ -1 +1 @@ -Subproject commit 802ffbae9af22d986226bc1c20d7d96aaf25d6b9 +Subproject commit 0e6407be7081341526f815a4d70e7912db276a98