From 9cc4fd683d4bf11193ec02a1af89b77111e38c0f Mon Sep 17 00:00:00 2001 From: Scott Williams Date: Tue, 12 Jun 2018 22:26:45 +0100 Subject: [PATCH 01/21] add optermised drawing path with cached glyph rendering --- .../Drawing/Processors/FillRegionProcessor.cs | 19 +- .../Text/DrawTextExtensions.Path.cs | 30 +- .../Processing/Text/DrawTextExtensions.cs | 32 +- .../Processors/DrawTextOnPathProcessor.cs | 140 ++++++ .../Text/Processors/DrawTextProcessor.cs | 458 ++++++++++++++++++ .../Processing/Text/TextGraphicsOptions.cs | 19 + .../ImageSharp.Benchmarks/Drawing/DrawText.cs | 101 ++++ .../OldProcessors/DrawTextProcessorV1.cs | 138 ++++++ .../Drawing/Text/DrawText.Path.cs | 61 +-- .../ImageSharp.Tests/Drawing/Text/DrawText.cs | 101 ++-- .../Drawing/Text/DrawTextOnImageTests.cs | 22 +- .../ImageSharp.Tests/ImageSharp.Tests.csproj | 6 + 12 files changed, 933 insertions(+), 194 deletions(-) create mode 100644 src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextOnPathProcessor.cs create mode 100644 src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs create mode 100644 tests/ImageSharp.Benchmarks/Drawing/DrawText.cs create mode 100644 tests/ImageSharp.Benchmarks/Drawing/OldProcessors/DrawTextProcessorV1.cs diff --git a/src/ImageSharp.Drawing/Processing/Drawing/Processors/FillRegionProcessor.cs b/src/ImageSharp.Drawing/Processing/Drawing/Processors/FillRegionProcessor.cs index 95ac3fe29..6eb6a15d0 100644 --- a/src/ImageSharp.Drawing/Processing/Drawing/Processors/FillRegionProcessor.cs +++ b/src/ImageSharp.Drawing/Processing/Drawing/Processors/FillRegionProcessor.cs @@ -37,22 +37,29 @@ namespace SixLabors.ImageSharp.Processing.Drawing.Processors } /// - /// Gets the brush. + /// Initializes a new instance of the class. + /// + public FillRegionProcessor() + { + } + + /// + /// Gets or sets the brush. /// - public IBrush Brush { get; } + public IBrush Brush { get; set; } /// - /// Gets the region that this processor applies to. + /// Gets or sets the region that this processor applies to. /// - public Region Region { get; } + public Region Region { get; set; } /// - /// Gets the options. + /// Gets or sets the options. /// /// /// The options. /// - public GraphicsOptions Options { get; } + public GraphicsOptions Options { get; set; } /// protected override void OnFrameApply(ImageFrame source, Rectangle sourceRectangle, Configuration configuration) diff --git a/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.Path.cs b/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.Path.cs index 9de73afcc..e0c133d50 100644 --- a/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.Path.cs +++ b/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.Path.cs @@ -6,6 +6,7 @@ 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.Shapes; namespace SixLabors.ImageSharp.Processing.Text @@ -147,33 +148,6 @@ namespace SixLabors.ImageSharp.Processing.Text /// 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; - } + => source.ApplyProcessor(new DrawTextOnPathProcessor(options, text, font, brush, pen, path)); } } \ 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..ed7a7bbfa 100644 --- a/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.cs +++ b/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.cs @@ -6,6 +6,7 @@ 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; @@ -16,8 +17,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 +149,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/DrawTextOnPathProcessor.cs b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextOnPathProcessor.cs new file mode 100644 index 000000000..c8a51865c --- /dev/null +++ b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextOnPathProcessor.cs @@ -0,0 +1,140 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System; +using System.Threading.Tasks; +using SixLabors.Fonts; +using SixLabors.ImageSharp.Advanced; +using SixLabors.ImageSharp.Memory; +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Primitives; +using SixLabors.ImageSharp.Processing.Drawing.Brushes; +using SixLabors.ImageSharp.Processing.Drawing.Pens; +using SixLabors.ImageSharp.Processing.Drawing.Processors; +using SixLabors.ImageSharp.Processing.Processors; +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 DrawTextOnPathProcessor : ImageProcessor + where TPixel : struct, IPixel + { + private FillRegionProcessor fillRegionProcessor = null; + + /// + /// 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 path on which to draw the text along. + public DrawTextOnPathProcessor(TextGraphicsOptions options, string text, Font font, IBrush brush, IPen pen, IPath path) + { + this.Brush = brush; + this.Options = options; + this.Text = text; + this.Pen = pen; + this.Font = font; + this.Path = path; + } + + /// + /// Gets or sets the brush. + /// + public IBrush Brush { get; set; } + + /// + /// Gets or sets the options + /// + private TextGraphicsOptions Options { get; set; } + + /// + /// Gets or sets the text + /// + private string Text { get; set; } + + /// + /// Gets or sets the pen used for outlining the text, if Null then we will not outline + /// + public IPen Pen { get; set; } + + /// + /// Gets or sets the font used to render the text. + /// + public Font Font { get; set; } + + /// + /// Gets or sets the path to draw the text along. + /// + public IPath Path { get; set; } + + 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) + { + ApplyKerning = this.Options.ApplyKerning, + TabWidth = this.Options.TabWidth, + WrappingWidth = this.Options.WrapTextWidth, + HorizontalAlignment = this.Options.HorizontalAlignment, + VerticalAlignment = this.Options.VerticalAlignment + }; + + IPathCollection glyphs = TextBuilder.GenerateGlyphs(this.Text, this.Path, style); + + var pathOptions = (GraphicsOptions)this.Options; + if (this.Brush != null) + { + // we will reuse the processor for all fill operations to reduce allocations + if (this.fillRegionProcessor == null) + { + this.fillRegionProcessor = new FillRegionProcessor() + { + Brush = this.Brush, + Options = pathOptions + }; + } + + foreach (IPath p in glyphs) + { + this.fillRegionProcessor.Region = new ShapeRegion(p); + this.fillRegionProcessor.Apply(source, sourceRectangle); + } + } + + if (this.Pen != null) + { + // we will reuse the processor for all fill operations to reduce allocations + if (this.fillRegionProcessor == null) + { + this.fillRegionProcessor = new FillRegionProcessor() + { + Brush = this.Brush, + Options = pathOptions + }; + } + + foreach (IPath p in glyphs) + { + this.fillRegionProcessor.Region = new ShapePath(p, this.Pen); + this.fillRegionProcessor.Apply(source, sourceRectangle); + } + } + } + + /// + 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 + } + } +} \ 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..b029ff516 --- /dev/null +++ b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs @@ -0,0 +1,458 @@ +// Copyright (c) Six Labors and contributors. +// Licensed under the Apache License, Version 2.0. + +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using SixLabors.Fonts; +using SixLabors.ImageSharp.Advanced; +using SixLabors.ImageSharp.Memory; +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Primitives; +using SixLabors.ImageSharp.Processing.Drawing.Brushes; +using SixLabors.ImageSharp.Processing.Drawing.Pens; +using SixLabors.ImageSharp.Processing.Drawing.Processors; +using SixLabors.ImageSharp.Processing.Processors; +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 FillRegionProcessor fillRegionProcessor = null; + + 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) + { + this.Brush = brush; + this.Options = options; + this.Text = text; + this.Pen = pen; + this.Font = font; + this.Location = location; + } + + /// + /// Gets or sets the brush. + /// + public IBrush Brush { get; set; } + + /// + /// Gets or sets the options + /// + public TextGraphicsOptions Options { get; set; } + + /// + /// Gets or sets the text + /// + public string Text { get; set; } + + /// + /// Gets or sets the pen used for outlining the text, if Null then we will not outline + /// + public IPen Pen { get; set; } + + /// + /// Gets or sets the font used to render the text. + /// + public Font Font { get; set; } + + /// + /// Gets or sets the location to draw the text at. + /// + public PointF Location { get; set; } + + protected override void BeforeImageApply(Image source, Rectangle sourceRectangle) + { + base.BeforeImageApply(source, sourceRectangle); + + // user slow path if pen is set and fast render for brush only rendering + + // 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 + }; + + if (this.Pen != null) + { + IPathCollection glyphs = TextBuilder.GenerateGlyphs(this.Text, style); + + var pathOptions = (GraphicsOptions)this.Options; + if (this.Brush != null) + { + // we will reuse the processor for all fill operations to reduce allocations + if (this.fillRegionProcessor == null) + { + this.fillRegionProcessor = new FillRegionProcessor() + { + Brush = this.Brush, + Options = pathOptions + }; + } + + foreach (IPath p in glyphs) + { + this.fillRegionProcessor.Region = new ShapeRegion(p); + this.fillRegionProcessor.Apply(source, sourceRectangle); + } + } + + // we will reuse the processor for all fill operations to reduce allocations + if (this.fillRegionProcessor == null) + { + this.fillRegionProcessor = new FillRegionProcessor() + { + Brush = this.Brush, + Options = pathOptions + }; + } + + foreach (IPath p in glyphs) + { + this.fillRegionProcessor.Region = new ShapePath(p, this.Pen); + this.fillRegionProcessor.Apply(source, sourceRectangle); + } + } + else + { + this.textRenderer = new CachingGlyphRenderer(source.GetMemoryManager()); + 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 + if (this.Pen == null && this.Brush != null && this.textRenderer != null && this.textRenderer.Operations.Count > 0) + { + // we have rendered at the image level now we can draw + List operations = this.textRenderer.Operations; + + using (BrushApplicator app = this.Brush.CreateApplicator(source, sourceRectangle, this.textRenderer.Options)) + { + foreach (DrawingOperation operation in operations) + { + IBuffer2D buffer = operation.Map; + int startY = operation.Location.Y; + int startX = operation.Location.X; + int end = operation.Map.Height; + for (int row = 0; row < end; row++) + { + int y = startY + row; + app.Apply(buffer.GetRowSpan(row), startX, y); + } + } + } + } + } + + private struct DrawingOperation + { + public IBuffer2D Map { get; set; } + + public Point Location { get; set; } + } + + private class CachingGlyphRenderer : IGlyphRenderer, IDisposable + { + private PathBuilder builder; + + private Point currentRenderPosition = default(Point); + private int currentRenderingGlyph = 0; + + private PointF currentPoint = default(PointF); + private Dictionary> glyphMap = new Dictionary>(); + + public CachingGlyphRenderer(MemoryManager memoryManager) + { + this.MemoryManager = memoryManager; + this.builder = new PathBuilder(); + } + + public List Operations { get; } = new List(); + + public MemoryManager MemoryManager { get; internal set; } + + public GraphicsOptions Options { get; internal set; } + + public void BeginFigure() + { + this.builder.StartFigure(); + } + + public bool BeginGlyph(RectangleF bounds, int cacheKey) + { + this.currentRenderPosition = Point.Truncate(bounds.Location); + this.currentRenderingGlyph = cacheKey; + + if (this.glyphMap.ContainsKey(this.currentRenderingGlyph)) + { + // we have already drawn the glyph vectors skip trying again + 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, -(int)bounds.Y)); + + return true; + } + + public void BeginText(RectangleF bounds) + { + // not concerned about this one + this.Operations.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> m in this.glyphMap) + { + m.Value.Dispose(); + } + } + + public void EndFigure() + { + this.builder.CloseFigure(); + } + + public void EndGlyph() + { + if (!this.glyphMap.ContainsKey(this.currentRenderingGlyph)) + { + this.RenderToCache(); + } + + this.Operations.Add(new DrawingOperation + { + Location = this.currentRenderPosition, + Map = this.glyphMap[this.currentRenderingGlyph] + }); + } + + private void RenderToCache() + { + IPath path = this.builder.Build(); + + var size = Rectangle.Ceiling(path.Bounds); + 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.MemoryManager.Allocate2D(size.Width + 1, size.Height + 1, true); + this.glyphMap.Add(this.currentRenderingGlyph, fullBuffer); + using (IBuffer bufferBacking = this.MemoryManager.Allocate(path.MaxIntersections)) + using (IBuffer rowIntersectionBuffer = this.MemoryManager.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.Span; + Span buffer = bufferBacking.Span; + 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(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; + } + } + } + } + } + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Swap(Span data, int left, int right) + { + float tmp = data[left]; + data[left] = data[right]; + data[right] = tmp; + } + + private static void QuickSort(Span data) + { + QuickSort(data, 0, data.Length - 1); + } + + private static void QuickSort(Span data, int lo, int hi) + { + if (lo < hi) + { + int p = Partition(data, lo, hi); + QuickSort(data, lo, p); + QuickSort(data, p + 1, hi); + } + } + + private static int Partition(Span data, int lo, int hi) + { + float pivot = data[lo]; + int i = lo - 1; + int j = hi + 1; + while (true) + { + do + { + i = i + 1; + } + while (data[i] < pivot && i < hi); + + do + { + j = j - 1; + } + while (data[j] > pivot && j > lo); + + if (i >= j) + { + return j; + } + + Swap(data, i, j); + } + } + + 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; + } + } + } +} \ 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/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/OldProcessors/DrawTextProcessorV1.cs b/tests/ImageSharp.Benchmarks/Drawing/OldProcessors/DrawTextProcessorV1.cs new file mode 100644 index 000000000..3faaec2c2 --- /dev/null +++ b/tests/ImageSharp.Benchmarks/Drawing/OldProcessors/DrawTextProcessorV1.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using System.Text; +using SixLabors.Fonts; +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Primitives; +using SixLabors.ImageSharp.Processing.Drawing.Brushes; +using SixLabors.ImageSharp.Processing.Drawing.Pens; +using SixLabors.ImageSharp.Processing.Drawing.Processors; +using SixLabors.ImageSharp.Processing.Processors; +using SixLabors.ImageSharp.Processing.Text; +using SixLabors.Primitives; +using SixLabors.Shapes; + +namespace SixLabors.ImageSharp.Benchmarks.Drawing.OldProcessors +{ + + /// + /// 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 FillRegionProcessor fillRegionProcessor = null; + + /// + /// 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) + { + this.Brush = brush; + this.Options = options; + this.Text = text; + this.Pen = pen; + this.Font = font; + this.Location = location; + } + + /// + /// Gets or sets the brush. + /// + public IBrush Brush { get; set; } + + /// + /// Gets or sets the options + /// + public TextGraphicsOptions Options { get; set; } + + /// + /// Gets or sets the text + /// + public string Text { get; set; } + + /// + /// Gets or sets the pen used for outlining the text, if Null then we will not outline + /// + public IPen Pen { get; set; } + + /// + /// Gets or sets the font used to render the text. + /// + public Font Font { get; set; } + + /// + /// Gets or sets the location to draw the text at. + /// + public PointF Location { get; set; } + + 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 + }; + + IPathCollection glyphs = TextBuilder.GenerateGlyphs(this.Text, style); + + var pathOptions = (GraphicsOptions)this.Options; + if (this.Brush != null) + { + // we will reuse the processor for all fill operations to reduce allocations + if (this.fillRegionProcessor == null) + { + this.fillRegionProcessor = new FillRegionProcessor() + { + Brush = this.Brush, + Options = pathOptions + }; + } + + foreach (IPath p in glyphs) + { + this.fillRegionProcessor.Region = new ShapeRegion(p); + this.fillRegionProcessor.Apply(source, sourceRectangle); + } + } + + if (this.Pen != null) + { + // we will reuse the processor for all fill operations to reduce allocations + if (this.fillRegionProcessor == null) + { + this.fillRegionProcessor = new FillRegionProcessor() + { + Brush = this.Brush, + Options = pathOptions + }; + } + + foreach (IPath p in glyphs) + { + this.fillRegionProcessor.Region = new ShapePath(p, this.Pen); + this.fillRegionProcessor.Apply(source, sourceRectangle); + } + } + } + + /// + 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 + } + } +} diff --git a/tests/ImageSharp.Tests/Drawing/Text/DrawText.Path.cs b/tests/ImageSharp.Tests/Drawing/Text/DrawText.Path.cs index 4649bee6b..d352489b8 100644 --- a/tests/ImageSharp.Tests/Drawing/Text/DrawText.Path.cs +++ b/tests/ImageSharp.Tests/Drawing/Text/DrawText.Path.cs @@ -8,6 +8,7 @@ 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.Shapes; using Xunit; @@ -44,9 +45,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text null, this.path); - this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + this.Verify>(0); } [Fact] @@ -54,9 +53,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { this.operations.DrawText("123", this.Font, Brushes.Solid(Rgba32.Red), null, this.path); - this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + this.Verify>(0); } [Fact] @@ -64,9 +61,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { this.operations.DrawText(new TextGraphicsOptions(true), "123", this.Font, Brushes.Solid(Rgba32.Red), this.path); - this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + this.Verify>(0); } [Fact] @@ -74,9 +69,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { this.operations.DrawText("123", this.Font, Brushes.Solid(Rgba32.Red), this.path); - this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + this.Verify>(0); } [Fact] @@ -84,9 +77,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { this.operations.DrawText(new TextGraphicsOptions(true), "123", this.Font, Rgba32.Red, this.path); - 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 +88,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { this.operations.DrawText("123", this.Font, Rgba32.Red, this.path); - FillRegionProcessor processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + DrawTextOnPathProcessor processor = this.Verify>(0); SolidBrush brush = Assert.IsType>(processor.Brush); Assert.Equal(Rgba32.Red, brush.Color); @@ -116,9 +105,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text Pens.Dash(Rgba32.Red, 1), this.path); - var processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + var processor = this.Verify>(0); } [Fact] @@ -126,9 +113,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { 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); + var processor = this.Verify>(0); } [Fact] @@ -136,9 +121,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { 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); + var processor = this.Verify>(0); } [Fact] @@ -146,9 +129,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { this.operations.DrawText("123", this.Font, Pens.Dash(Rgba32.Red, 1), this.path); - FillRegionProcessor processor = this.Verify>(0); - this.Verify>(1); - this.Verify>(2); + DrawTextOnPathProcessor processor = this.Verify>(0); } [Fact] @@ -162,12 +143,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text 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); + var processor = this.Verify>(0); } [Fact] @@ -175,12 +151,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { 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); + var processor = this.Verify>(0); } [Fact] @@ -194,8 +165,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text Pens.Dash(Rgba32.Red, 1), this.path); - var processor = this.Verify>(0); - this.Verify>(1); + var processor = this.Verify>(0); } [Fact] @@ -203,8 +173,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { 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); + var processor = this.Verify>(0); } } } 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..f90d5996e 100644 --- a/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs +++ b/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs @@ -17,7 +17,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text using System; using System.Linq; using System.Text; - + using SixLabors.ImageSharp.Processing.Drawing.Brushes.GradientBrushes; using SixLabors.Primitives; [GroupOutput("Drawing/Text")] @@ -29,7 +29,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text private const string TestText2 = "THISISTESTWORDS "; - + [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)] @@ -51,9 +51,9 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text provider.VerifyOperation( img => - { - img.Mutate(c => c.DrawText(text, new Font(font, fontSize), color, new PointF(x, y))); - }, + { + img.Mutate(c => c.DrawText(text, new Font(font, fontSize), color, new PointF(x, y))); + }, $"{fontName}-{fontSize}-{fnDisplayText}-({x},{y})", appendPixelTypeToFileName: false, appendSourceFileOrDescription: true); @@ -84,12 +84,12 @@ 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( 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 From 6d92b4f83ac3172cad6a110b986ba7533e4bc55d Mon Sep 17 00:00:00 2001 From: Scott Williams Date: Wed, 13 Jun 2018 18:23:43 +0100 Subject: [PATCH 02/21] update reference images --- tests/Images/External | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Images/External b/tests/Images/External index eb40b3c03..802ffbae9 160000 --- a/tests/Images/External +++ b/tests/Images/External @@ -1 +1 @@ -Subproject commit eb40b3c039dd8c8ca448cb8073a59ca178901e9f +Subproject commit 802ffbae9af22d986226bc1c20d7d96aaf25d6b9 From 02baa60e89134b4baf89e6ca866f87315f66a278 Mon Sep 17 00:00:00 2001 From: Scott Williams Date: Wed, 13 Jun 2018 18:47:31 +0100 Subject: [PATCH 03/21] really update reference images this time --- tests/Images/External | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Images/External b/tests/Images/External index 802ffbae9..443db93ff 160000 --- a/tests/Images/External +++ b/tests/Images/External @@ -1 +1 @@ -Subproject commit 802ffbae9af22d986226bc1c20d7d96aaf25d6b9 +Subproject commit 443db93ffdb175dd0ef67eb8f0c525cc9ad59083 From 121f1edce6c5d10317fb6888c1aa1f78f0144035 Mon Sep 17 00:00:00 2001 From: Scott Williams Date: Thu, 14 Jun 2018 22:11:05 +0100 Subject: [PATCH 04/21] ensure pen code path is tested --- .../Text/Processors/DrawTextProcessor.cs | 2 +- .../Drawing/Text/DrawTextOnImageTests.cs | 30 +++++++++++++++++++ tests/Images/External | 2 +- 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs index b029ff516..8d51f4f44 100644 --- a/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs +++ b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs @@ -124,7 +124,7 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors { this.fillRegionProcessor = new FillRegionProcessor() { - Brush = this.Brush, + Brush = this.Pen.StrokeFill, Options = pathOptions }; } diff --git a/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs b/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs index f90d5996e..5440eb8db 100644 --- a/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs +++ b/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs @@ -18,6 +18,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text using System.Linq; using System.Text; using SixLabors.ImageSharp.Processing.Drawing.Brushes.GradientBrushes; + using SixLabors.ImageSharp.Processing.Drawing.Pens; using SixLabors.Primitives; [GroupOutput("Drawing/Text")] @@ -101,6 +102,35 @@ 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(400, 40, "White", PixelTypes.Rgba32, 20, 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); + string fnDisplayText = text.Replace("\n", ""); + fnDisplayText = fnDisplayText.Substring(0, Math.Min(fnDisplayText.Length, 4)); + TPixel color = NamedColors.Black; + + provider.VerifyOperation( + img => + { + img.Mutate(c => c.DrawText(text, new Font(font, fontSize),null, Pens.Solid(color, 1), new PointF(x, y))); + }, + $"pen_{fontName}-{fontSize}-{fnDisplayText}-({x},{y})", + appendPixelTypeToFileName: false, + appendSourceFileOrDescription: true); + } + private static string Repeat(string str, int times) => string.Concat(Enumerable.Repeat(str, times)); private static Font CreateFont(string fontName, int size) diff --git a/tests/Images/External b/tests/Images/External index 443db93ff..07cdbcfca 160000 --- a/tests/Images/External +++ b/tests/Images/External @@ -1 +1 @@ -Subproject commit 443db93ffdb175dd0ef67eb8f0c525cc9ad59083 +Subproject commit 07cdbcfca121081eae97d6a9cd0e230c653eeb39 From db88844711b60b890d2e7a4c5b6b35445a85cbb1 Mon Sep 17 00:00:00 2001 From: Scott Williams Date: Fri, 15 Jun 2018 18:07:02 +0100 Subject: [PATCH 05/21] increase tolerance on tests --- tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs b/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs index 5440eb8db..8af374435 100644 --- a/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs +++ b/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs @@ -19,6 +19,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text using System.Text; using SixLabors.ImageSharp.Processing.Drawing.Brushes.GradientBrushes; using SixLabors.ImageSharp.Processing.Drawing.Pens; + using SixLabors.ImageSharp.Tests.TestUtilities.ImageComparison; using SixLabors.Primitives; [GroupOutput("Drawing/Text")] @@ -122,6 +123,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text TPixel color = NamedColors.Black; provider.VerifyOperation( + ImageComparer.Tolerant(perPixelManhattanThreshold: 16), img => { img.Mutate(c => c.DrawText(text, new Font(font, fontSize),null, Pens.Solid(color, 1), new PointF(x, y))); From e43a8dbc2c554ecdbafebf265831442f7a5ea0b6 Mon Sep 17 00:00:00 2001 From: Scott Williams Date: Fri, 15 Jun 2018 21:46:58 +0100 Subject: [PATCH 06/21] apply optermised font rendering path to glyphs outlines --- .../ImageSharp.Drawing.csproj | 2 +- .../Text/Processors/DrawTextProcessor.cs | 190 ++++++++++-------- .../Drawing/DrawTextOutline.cs | 99 +++++++++ .../Drawing/Text/DrawTextOnImageTests.cs | 3 +- 4 files changed, 209 insertions(+), 85 deletions(-) create mode 100644 tests/ImageSharp.Benchmarks/Drawing/DrawTextOutline.cs diff --git a/src/ImageSharp.Drawing/ImageSharp.Drawing.csproj b/src/ImageSharp.Drawing/ImageSharp.Drawing.csproj index 30ca57b59..3776830ae 100644 --- a/src/ImageSharp.Drawing/ImageSharp.Drawing.csproj +++ b/src/ImageSharp.Drawing/ImageSharp.Drawing.csproj @@ -39,7 +39,7 @@ - + All diff --git a/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs index 8d51f4f44..a8b5e863b 100644 --- a/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs +++ b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs @@ -26,8 +26,6 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors internal class DrawTextProcessor : ImageProcessor where TPixel : struct, IPixel { - private FillRegionProcessor fillRegionProcessor = null; - private CachingGlyphRenderer textRenderer; /// @@ -83,8 +81,6 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors { base.BeforeImageApply(source, sourceRectangle); - // user slow path if pen is set and fast render for brush only rendering - // 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) { @@ -95,52 +91,9 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors VerticalAlignment = this.Options.VerticalAlignment }; - if (this.Pen != null) - { - IPathCollection glyphs = TextBuilder.GenerateGlyphs(this.Text, style); - - var pathOptions = (GraphicsOptions)this.Options; - if (this.Brush != null) - { - // we will reuse the processor for all fill operations to reduce allocations - if (this.fillRegionProcessor == null) - { - this.fillRegionProcessor = new FillRegionProcessor() - { - Brush = this.Brush, - Options = pathOptions - }; - } - - foreach (IPath p in glyphs) - { - this.fillRegionProcessor.Region = new ShapeRegion(p); - this.fillRegionProcessor.Apply(source, sourceRectangle); - } - } - - // we will reuse the processor for all fill operations to reduce allocations - if (this.fillRegionProcessor == null) - { - this.fillRegionProcessor = new FillRegionProcessor() - { - Brush = this.Pen.StrokeFill, - Options = pathOptions - }; - } - - foreach (IPath p in glyphs) - { - this.fillRegionProcessor.Region = new ShapePath(p, this.Pen); - this.fillRegionProcessor.Apply(source, sourceRectangle); - } - } - else - { - this.textRenderer = new CachingGlyphRenderer(source.GetMemoryManager()); - this.textRenderer.Options = (GraphicsOptions)this.Options; - TextRenderer.RenderTextTo(this.textRenderer, this.Text, style); - } + this.textRenderer = new CachingGlyphRenderer(source.GetMemoryManager(), 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) @@ -154,23 +107,26 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors 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 - if (this.Pen == null && this.Brush != null && this.textRenderer != null && this.textRenderer.Operations.Count > 0) - { - // we have rendered at the image level now we can draw - List operations = this.textRenderer.Operations; + Draw(this.textRenderer.FillOperations, this.Brush); + Draw(this.textRenderer.OutlineOperations, this.Pen?.StrokeFill); - using (BrushApplicator app = this.Brush.CreateApplicator(source, sourceRectangle, this.textRenderer.Options)) + void Draw(List operations, IBrush brush) + { + if (operations?.Count > 0) { - foreach (DrawingOperation operation in operations) + using (BrushApplicator app = brush.CreateApplicator(source, sourceRectangle, this.textRenderer.Options)) { - IBuffer2D buffer = operation.Map; - int startY = operation.Location.Y; - int startX = operation.Location.X; - int end = operation.Map.Height; - for (int row = 0; row < end; row++) + foreach (DrawingOperation operation in operations) { - int y = startY + row; - app.Apply(buffer.GetRowSpan(row), startX, y); + IBuffer2D buffer = operation.Map; + int startY = operation.Location.Y; + int startX = operation.Location.X; + int end = operation.Map.Height; + for (int row = 0; row < end; row++) + { + int y = startY + row; + app.Apply(buffer.GetRowSpan(row), startX, y); + } } } } @@ -192,18 +148,42 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors private int currentRenderingGlyph = 0; private PointF currentPoint = default(PointF); - private Dictionary> glyphMap = new Dictionary>(); - - public CachingGlyphRenderer(MemoryManager memoryManager) + private HashSet renderedGlyphs = new HashSet(); + private Dictionary> glyphMap; + private Dictionary> glyphMapPen; + private bool renderOutline = false; + private bool renderFill = false; + private bool raterizationRequired = false; + + public CachingGlyphRenderer(MemoryManager memoryManager, int size, IPen pen, bool renderFill) { this.MemoryManager = memoryManager; + this.Pen = pen; + this.renderFill = renderFill; + this.renderOutline = pen != null; + if (this.renderFill) + { + this.FillOperations = new List(size); + this.glyphMap = new Dictionary>(); + } + + if (this.renderOutline) + { + this.OutlineOperations = new List(size); + this.glyphMapPen = new Dictionary>(); + } + this.builder = new PathBuilder(); } - public List Operations { get; } = new List(); + public List FillOperations { get; } + + public List OutlineOperations { get; } public MemoryManager MemoryManager { get; internal set; } + public IPen Pen { get; internal set; } + public GraphicsOptions Options { get; internal set; } public void BeginFigure() @@ -215,10 +195,10 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors { this.currentRenderPosition = Point.Truncate(bounds.Location); this.currentRenderingGlyph = cacheKey; - - if (this.glyphMap.ContainsKey(this.currentRenderingGlyph)) + if (this.renderedGlyphs.Contains(cacheKey)) { // we have already drawn the glyph vectors skip trying again + this.raterizationRequired = false; return false; } @@ -228,13 +208,15 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors // 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, -(int)bounds.Y)); + this.raterizationRequired = true; return true; } public void BeginText(RectangleF bounds) { // not concerned about this one - this.Operations.Clear(); + this.OutlineOperations?.Clear(); + this.FillOperations?.Clear(); } public void CubicBezierTo(PointF secondControlPoint, PointF thirdControlPoint, PointF point) @@ -245,9 +227,20 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors public void Dispose() { - foreach (KeyValuePair> m in this.glyphMap) + if (this.renderFill) + { + foreach (KeyValuePair> m in this.glyphMap) + { + m.Value.Dispose(); + } + } + + if (this.renderOutline) { - m.Value.Dispose(); + foreach (KeyValuePair> m in this.glyphMapPen) + { + m.Value.Dispose(); + } } } @@ -258,22 +251,53 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors public void EndGlyph() { - if (!this.glyphMap.ContainsKey(this.currentRenderingGlyph)) + // has the glyoh been rendedered already???? + if (this.raterizationRequired) { - this.RenderToCache(); + IPath path = this.builder.Build(); + if (this.renderFill) + { + this.glyphMap[this.currentRenderingGlyph] = 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); + } + + this.glyphMapPen[this.currentRenderingGlyph] = this.Render(path); + } + + this.renderedGlyphs.Add(this.currentRenderingGlyph); } - this.Operations.Add(new DrawingOperation + if (this.renderFill) { - Location = this.currentRenderPosition, - Map = this.glyphMap[this.currentRenderingGlyph] - }); + this.FillOperations.Add(new DrawingOperation + { + Location = this.currentRenderPosition, + Map = this.glyphMap[this.currentRenderingGlyph] + }); + } + + if (this.renderOutline) + { + this.OutlineOperations.Add(new DrawingOperation + { + Location = this.currentRenderPosition, + Map = this.glyphMapPen[this.currentRenderingGlyph] + }); + } } - private void RenderToCache() + private Buffer2D Render(IPath path) { - IPath path = this.builder.Build(); - var size = Rectangle.Ceiling(path.Bounds); float subpixelCount = 4; float offset = 0.5f; @@ -289,7 +313,7 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors // take the path inside the path builder, scan thing and generate a Buffer2d representing the glyph and cache it. Buffer2D fullBuffer = this.MemoryManager.Allocate2D(size.Width + 1, size.Height + 1, true); - this.glyphMap.Add(this.currentRenderingGlyph, fullBuffer); + using (IBuffer bufferBacking = this.MemoryManager.Allocate(path.MaxIntersections)) using (IBuffer rowIntersectionBuffer = this.MemoryManager.Allocate(size.Width)) { @@ -379,6 +403,8 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors } } } + + return fullBuffer; } [MethodImpl(MethodImplOptions.AggressiveInlining)] 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.Tests/Drawing/Text/DrawTextOnImageTests.cs b/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs index 8af374435..cc7d8622a 100644 --- a/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs +++ b/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs @@ -106,7 +106,6 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text [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(400, 40, "White", PixelTypes.Rgba32, 20, 0, 0, "OpenSans-Regular.ttf", TestText)] [WithSolidFilledImages(1100, 200, "White", PixelTypes.Rgba32, 50, 150, 100, "OpenSans-Regular.ttf", TestText)] public void FontShapesAreRenderedCorrectlyWithAPen( TestImageProvider provider, @@ -123,7 +122,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text TPixel color = NamedColors.Black; provider.VerifyOperation( - ImageComparer.Tolerant(perPixelManhattanThreshold: 16), + ImageComparer.Tolerant(imageThreshold: 0.1f, perPixelManhattanThreshold: 20), img => { img.Mutate(c => c.DrawText(text, new Font(font, fontSize),null, Pens.Solid(color, 1), new PointF(x, y))); From 3896723bfbdaa0d0d483819cbb394048735c46d4 Mon Sep 17 00:00:00 2001 From: Scott Williams Date: Sun, 17 Jun 2018 10:59:17 +0100 Subject: [PATCH 07/21] additional tests around pen rendering with patterns --- .../Text/Processors/DrawTextProcessor.cs | 35 ++++++++++++++++--- .../Drawing/Text/DrawTextOnImageTests.cs | 33 ++++++++++++++++- tests/Images/External | 2 +- 3 files changed, 63 insertions(+), 7 deletions(-) diff --git a/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs index a8b5e863b..5681405bf 100644 --- a/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs +++ b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs @@ -121,11 +121,29 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors IBuffer2D 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; - for (int row = 0; row < end; row++) + + int maxHeight = source.Height - startY; + end = Math.Min(end, maxHeight); + + for (int row = fistRow; row < end; row++) { int y = startY + row; - app.Apply(buffer.GetRowSpan(row), startX, y); + Span span = buffer.GetRowSpan(row).Slice(offSetSpan); + app.Apply(span, startX, y); } } } @@ -146,7 +164,7 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors private Point currentRenderPosition = default(Point); private int currentRenderingGlyph = 0; - + private int offset = 0; private PointF currentPoint = default(PointF); private HashSet renderedGlyphs = new HashSet(); private Dictionary> glyphMap; @@ -161,6 +179,7 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors this.Pen = pen; this.renderFill = renderFill; this.renderOutline = pen != null; + this.offset = 2; if (this.renderFill) { this.FillOperations = new List(size); @@ -169,6 +188,7 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors if (this.renderOutline) { + this.offset = (int)MathF.Ceiling((pen.StrokeWidth * 2) + 2); this.OutlineOperations = new List(size); this.glyphMapPen = new Dictionary>(); } @@ -194,6 +214,9 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors public bool BeginGlyph(RectangleF bounds, int cacheKey) { 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.currentRenderingGlyph = cacheKey; if (this.renderedGlyphs.Contains(cacheKey)) { @@ -206,7 +229,7 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors 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, -(int)bounds.Y)); + this.builder.SetOrigin(new PointF(-(int)bounds.X + this.offset, -(int)bounds.Y + this.offset)); this.raterizationRequired = true; return true; @@ -298,7 +321,9 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors private Buffer2D Render(IPath path) { - var size = Rectangle.Ceiling(path.Bounds); + 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) diff --git a/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs b/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs index cc7d8622a..400917f7a 100644 --- a/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs +++ b/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs @@ -52,6 +52,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text TPixel color = NamedColors.Black; provider.VerifyOperation( + ImageComparer.Tolerant(imageThreshold: 0.1f, perPixelManhattanThreshold: 20), img => { img.Mutate(c => c.DrawText(text, new Font(font, fontSize), color, new PointF(x, y))); @@ -95,6 +96,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text TPixel color = NamedColors.Black; provider.VerifyOperation( + ImageComparer.Tolerant(imageThreshold: 0.1f, perPixelManhattanThreshold: 20), img => { img.Mutate(c => c.DrawText(textOptions, sb.ToString(), font, color, new PointF(10, 5))); @@ -125,7 +127,36 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text ImageComparer.Tolerant(imageThreshold: 0.1f, perPixelManhattanThreshold: 20), img => { - img.Mutate(c => c.DrawText(text, new Font(font, fontSize),null, Pens.Solid(color, 1), new PointF(x, y))); + img.Mutate(c => c.DrawText(text, new Font(font, fontSize), null, Pens.Solid(color, 1), new PointF(x, y))); + }, + $"pen_{fontName}-{fontSize}-{fnDisplayText}-({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); + string fnDisplayText = text.Replace("\n", ""); + fnDisplayText = fnDisplayText.Substring(0, Math.Min(fnDisplayText.Length, 4)); + TPixel color = NamedColors.Black; + + provider.VerifyOperation( + ImageComparer.Tolerant(imageThreshold: 0.1f, perPixelManhattanThreshold: 20), + img => + { + img.Mutate(c => c.DrawText(text, new Font(font, fontSize), null, Pens.DashDot(color, 3), new PointF(x, y))); }, $"pen_{fontName}-{fontSize}-{fnDisplayText}-({x},{y})", appendPixelTypeToFileName: false, diff --git a/tests/Images/External b/tests/Images/External index 07cdbcfca..09059fae2 160000 --- a/tests/Images/External +++ b/tests/Images/External @@ -1 +1 @@ -Subproject commit 07cdbcfca121081eae97d6a9cd0e230c653eeb39 +Subproject commit 09059fae2d8bea3a4c9288ab10fb184f1b648f40 From 886038928ba9439275bb06651657a23e6448cec2 Mon Sep 17 00:00:00 2001 From: Scott Williams Date: Sun, 17 Jun 2018 10:59:27 +0100 Subject: [PATCH 08/21] increase coverage on drawing path collections --- .../Drawing/Paths/DrawPathCollection.cs | 117 ++++++++++++++++++ 1 file changed, 117 insertions(+) create mode 100644 tests/ImageSharp.Tests/Drawing/Paths/DrawPathCollection.cs 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); + } + } + } +} From 5609f1bdb3df4a30d8ff54c3c53652c84345fe4c Mon Sep 17 00:00:00 2001 From: Scott Williams Date: Sun, 17 Jun 2018 11:07:24 +0100 Subject: [PATCH 09/21] fix api changes due to MemoryManager->MemoryAllocator rename --- .../Text/Processors/DrawTextOnPathProcessor.cs | 2 -- .../Processing/Text/Processors/DrawTextProcessor.cs | 12 ++++++------ 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextOnPathProcessor.cs b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextOnPathProcessor.cs index c8a51865c..6c33d306b 100644 --- a/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextOnPathProcessor.cs +++ b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextOnPathProcessor.cs @@ -4,8 +4,6 @@ using System; using System.Threading.Tasks; using SixLabors.Fonts; -using SixLabors.ImageSharp.Advanced; -using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Primitives; using SixLabors.ImageSharp.Processing.Drawing.Brushes; diff --git a/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs index 5681405bf..d00cba8a3 100644 --- a/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs +++ b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs @@ -7,13 +7,13 @@ using System.Runtime.CompilerServices; using System.Threading.Tasks; using SixLabors.Fonts; using SixLabors.ImageSharp.Advanced; -using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Primitives; using SixLabors.ImageSharp.Processing.Drawing.Brushes; using SixLabors.ImageSharp.Processing.Drawing.Pens; using SixLabors.ImageSharp.Processing.Drawing.Processors; using SixLabors.ImageSharp.Processing.Processors; +using SixLabors.Memory; using SixLabors.Primitives; using SixLabors.Shapes; @@ -91,7 +91,7 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors VerticalAlignment = this.Options.VerticalAlignment }; - this.textRenderer = new CachingGlyphRenderer(source.GetMemoryManager(), this.Text.Length, this.Pen, this.Brush != null); + 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); } @@ -173,7 +173,7 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors private bool renderFill = false; private bool raterizationRequired = false; - public CachingGlyphRenderer(MemoryManager memoryManager, int size, IPen pen, bool renderFill) + public CachingGlyphRenderer(MemoryAllocator memoryManager, int size, IPen pen, bool renderFill) { this.MemoryManager = memoryManager; this.Pen = pen; @@ -200,7 +200,7 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors public List OutlineOperations { get; } - public MemoryManager MemoryManager { get; internal set; } + public MemoryAllocator MemoryManager { get; internal set; } public IPen Pen { get; internal set; } @@ -355,8 +355,8 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors { var start = new PointF(path.Bounds.Left - 1, subPixel); var end = new PointF(path.Bounds.Right + 1, subPixel); - Span intersectionSpan = rowIntersectionBuffer.Span; - Span buffer = bufferBacking.Span; + Span intersectionSpan = rowIntersectionBuffer.GetSpan(); + Span buffer = bufferBacking.GetSpan(); int pointsFound = path.FindIntersections(start, end, intersectionSpan); if (pointsFound == 0) From 77bf952bbd69ba5ac77d0dfdc641a43abe07d353 Mon Sep 17 00:00:00 2001 From: Scott Williams Date: Sun, 17 Jun 2018 13:50:12 +0100 Subject: [PATCH 10/21] test drawing along path --- .../Primitives/ShapePath.cs | 2 +- .../Processors/DrawTextOnPathProcessor.cs | 25 +++-------- .../Drawing/Text/DrawTextOnImageTests.cs | 41 +++++++++++++++++++ tests/Images/External | 2 +- 4 files changed, 48 insertions(+), 22 deletions(-) diff --git a/src/ImageSharp.Drawing/Primitives/ShapePath.cs b/src/ImageSharp.Drawing/Primitives/ShapePath.cs index 2a569f061..7aae2bf8e 100644 --- a/src/ImageSharp.Drawing/Primitives/ShapePath.cs +++ b/src/ImageSharp.Drawing/Primitives/ShapePath.cs @@ -18,7 +18,7 @@ namespace SixLabors.ImageSharp.Primitives /// 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/Text/Processors/DrawTextOnPathProcessor.cs b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextOnPathProcessor.cs index 6c33d306b..1e703d1cc 100644 --- a/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextOnPathProcessor.cs +++ b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextOnPathProcessor.cs @@ -82,25 +82,18 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors { ApplyKerning = this.Options.ApplyKerning, TabWidth = this.Options.TabWidth, - WrappingWidth = this.Options.WrapTextWidth, + WrappingWidth = this.Path.Length, HorizontalAlignment = this.Options.HorizontalAlignment, VerticalAlignment = this.Options.VerticalAlignment }; IPathCollection glyphs = TextBuilder.GenerateGlyphs(this.Text, this.Path, style); + this.fillRegionProcessor = new FillRegionProcessor(); + this.fillRegionProcessor.Options = (GraphicsOptions)this.Options; - var pathOptions = (GraphicsOptions)this.Options; if (this.Brush != null) { - // we will reuse the processor for all fill operations to reduce allocations - if (this.fillRegionProcessor == null) - { - this.fillRegionProcessor = new FillRegionProcessor() - { - Brush = this.Brush, - Options = pathOptions - }; - } + this.fillRegionProcessor.Brush = this.Brush; foreach (IPath p in glyphs) { @@ -111,15 +104,7 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors if (this.Pen != null) { - // we will reuse the processor for all fill operations to reduce allocations - if (this.fillRegionProcessor == null) - { - this.fillRegionProcessor = new FillRegionProcessor() - { - Brush = this.Brush, - Options = pathOptions - }; - } + this.fillRegionProcessor.Brush = this.Pen.StrokeFill; foreach (IPath p in glyphs) { diff --git a/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs b/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs index 400917f7a..a1a9b0222 100644 --- a/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs +++ b/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs @@ -17,10 +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 @@ -163,6 +165,45 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text appendSourceFileOrDescription: true); } + + [Theory] + [WithSolidFilledImages(200, 100, "White", PixelTypes.Rgba32, 50, "SixLaborsSampleAB.woff", AB)] + [WithSolidFilledImages(900, 100, "White", PixelTypes.Rgba32, 50, "OpenSans-Regular.ttf", TestText)] + public void FontShapesAreRenderedCorrectlyAlongAPath( + TestImageProvider provider, + int fontSize, + string fontName, + string 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 colorOutline = NamedColors.Black; + TPixel colorFill = NamedColors.Gray; + + provider.VerifyOperation( + ImageComparer.Tolerant(imageThreshold: 0.1f, perPixelManhattanThreshold: 20), + img => + { + + IPath path = new Path(new LinearLineSegment(new Point(0, img.Height), new Point(img.Width, 0))); + img.Mutate(c => c.DrawText( + new TextGraphicsOptions { + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Top + } , + text, new Font(font, fontSize), + Brushes.Solid(colorFill) + , Pens.DashDot(colorOutline, 3), + path)); + }, + $"pen_{fontName}-{fontSize}-{fnDisplayText}", + appendPixelTypeToFileName: false, + appendSourceFileOrDescription: true); + } + private static string Repeat(string str, int times) => string.Concat(Enumerable.Repeat(str, times)); private static Font CreateFont(string fontName, int size) diff --git a/tests/Images/External b/tests/Images/External index 09059fae2..83f6cbab9 160000 --- a/tests/Images/External +++ b/tests/Images/External @@ -1 +1 @@ -Subproject commit 09059fae2d8bea3a4c9288ab10fb184f1b648f40 +Subproject commit 83f6cbab9a08b550c84bf931c95188341140516a From 31ce2836c047e8f3cd15a4cbada5fe5956bb45b1 Mon Sep 17 00:00:00 2001 From: Anton Firszov Date: Sun, 17 Jun 2018 15:06:18 +0200 Subject: [PATCH 11/21] format long lines in DrawTextExtensions.Path.cs --- .../Text/DrawTextExtensions.Path.cs | 94 ++++++++++++++----- 1 file changed, 70 insertions(+), 24 deletions(-) diff --git a/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.Path.cs b/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.Path.cs index e0c133d50..827d6b95f 100644 --- a/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.Path.cs +++ b/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.Path.cs @@ -28,9 +28,14 @@ namespace SixLabors.ImageSharp.Processing.Text /// /// 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); + 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. @@ -45,9 +50,15 @@ namespace SixLabors.ImageSharp.Processing.Text /// /// 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); + 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. @@ -61,9 +72,14 @@ namespace SixLabors.ImageSharp.Processing.Text /// /// 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); + 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. @@ -78,9 +94,15 @@ namespace SixLabors.ImageSharp.Processing.Text /// /// 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); + 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. @@ -94,9 +116,14 @@ namespace SixLabors.ImageSharp.Processing.Text /// /// 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); + 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. @@ -111,9 +138,15 @@ namespace SixLabors.ImageSharp.Processing.Text /// /// 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); + 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. @@ -128,9 +161,15 @@ namespace SixLabors.ImageSharp.Processing.Text /// /// 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); + 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. @@ -146,8 +185,15 @@ namespace SixLabors.ImageSharp.Processing.Text /// /// The . /// - public static IImageProcessingContext DrawText(this IImageProcessingContext source, TextGraphicsOptions options, string text, Font font, IBrush brush, IPen pen, IPath path) - where TPixel : struct, IPixel - => source.ApplyProcessor(new DrawTextOnPathProcessor(options, text, font, brush, pen, path)); + public static IImageProcessingContext DrawText( + this IImageProcessingContext source, + TextGraphicsOptions options, + string text, + Font font, + IBrush brush, + IPen pen, + IPath path) + where TPixel : struct, IPixel => + source.ApplyProcessor(new DrawTextOnPathProcessor(options, text, font, brush, pen, path)); } } \ No newline at end of file From 8a14fa0ab7ab7656f4d4992d123dbcf7a7e94048 Mon Sep 17 00:00:00 2001 From: Anton Firszov Date: Sun, 17 Jun 2018 16:21:50 +0200 Subject: [PATCH 12/21] add FontShapesAreRenderedCorrectlyAlongACirclePath() --- .../Drawing/Text/DrawTextOnImageTests.cs | 89 ++++++++++++++----- 1 file changed, 69 insertions(+), 20 deletions(-) diff --git a/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs b/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs index a1a9b0222..6922213f2 100644 --- a/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs +++ b/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs @@ -150,8 +150,6 @@ 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( @@ -160,15 +158,14 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text { img.Mutate(c => c.DrawText(text, new Font(font, fontSize), null, Pens.DashDot(color, 3), new PointF(x, y))); }, - $"pen_{fontName}-{fontSize}-{fnDisplayText}-({x},{y})", + $"pen_{fontName}-{fontSize}-{ToTestOutputDisplayText(text)}-({x},{y})", appendPixelTypeToFileName: false, appendSourceFileOrDescription: true); } - [Theory] [WithSolidFilledImages(200, 100, "White", PixelTypes.Rgba32, 50, "SixLaborsSampleAB.woff", AB)] - [WithSolidFilledImages(900, 100, "White", PixelTypes.Rgba32, 50, "OpenSans-Regular.ttf", TestText)] + [WithSolidFilledImages(900, 100, "White", PixelTypes.Rgba32, 50, "OpenSans-Regular.ttf", TestText)] public void FontShapesAreRenderedCorrectlyAlongAPath( TestImageProvider provider, int fontSize, @@ -176,36 +173,88 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text string 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 colorOutline = NamedColors.Black; TPixel colorFill = NamedColors.Gray; + TPixel colorOutline = NamedColors.Black; + IBrush fillBrush = Brushes.Solid(colorFill); + IPen outlinePen = Pens.DashDot(colorOutline, 3); + provider.VerifyOperation( + ImageComparer.Tolerant(imageThreshold: 0.1f, perPixelManhattanThreshold: 20), + img => + { + IPath path = new Path(new LinearLineSegment(new Point(0, img.Height), new Point(img.Width, 0))); + img.Mutate( + c => + { + c.DrawText( + new TextGraphicsOptions + { + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Top + }, + text, + new Font(font, fontSize), + fillBrush, + outlinePen, + path); + }); + }, + $"pen_{fontName}-{fontSize}-{ToTestOutputDisplayText(text)}", + appendPixelTypeToFileName: false, + appendSourceFileOrDescription: true); + } + + [Theory] + [WithSolidFilledImages(600, 600, "White", PixelTypes.Rgba32, 50, "OpenSans-Regular.ttf", TestText)] + public void FontShapesAreRenderedCorrectlyAlongACirclePath( + TestImageProvider provider, + int fontSize, + string fontName, + string text) + where TPixel : struct, IPixel + { + + Font font = CreateFont(fontName, fontSize); + TPixel colorFill = NamedColors.Black; + IBrush fillBrush = Brushes.Solid(colorFill); + provider.VerifyOperation( ImageComparer.Tolerant(imageThreshold: 0.1f, perPixelManhattanThreshold: 20), img => { + int w = (int)(img.Width * 0.6); + int h = (int)(img.Height * 0.6); + IPath path = new EllipsePolygon(img.Width/2, img.Height/2, w, h); - IPath path = new Path(new LinearLineSegment(new Point(0, img.Height), new Point(img.Width, 0))); - img.Mutate(c => c.DrawText( - new TextGraphicsOptions { - HorizontalAlignment = HorizontalAlignment.Center, - VerticalAlignment = VerticalAlignment.Top - } , - text, new Font(font, fontSize), - Brushes.Solid(colorFill) - , Pens.DashDot(colorOutline, 3), - path)); + img.Mutate(c => + { + c.DrawText( + new TextGraphicsOptions + { + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Top + }, + text, + new Font(font, fontSize), + fillBrush, + path); + }); }, - $"pen_{fontName}-{fontSize}-{fnDisplayText}", + $"pen_{fontName}-{fontSize}-{ToTestOutputDisplayText(text)}", 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(); From ed1a70d0524fa45543e56532d896b3e4a1176f1e Mon Sep 17 00:00:00 2001 From: Anton Firszov Date: Sun, 17 Jun 2018 16:28:52 +0200 Subject: [PATCH 13/21] update submodule, fine-tune test tolerance --- .../Drawing/Text/DrawTextOnImageTests.cs | 23 ++++++++----------- tests/Images/External | 2 +- 2 files changed, 11 insertions(+), 14 deletions(-) diff --git a/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs b/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs index 6922213f2..ef6dc40f0 100644 --- a/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs +++ b/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs @@ -34,6 +34,8 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text private const string TestText2 = "THISISTESTWORDS "; + public static ImageComparer TextDrawingComparer = ImageComparer.TolerantPercentage(0.01f); + [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)] @@ -49,17 +51,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( - ImageComparer.Tolerant(imageThreshold: 0.1f, perPixelManhattanThreshold: 20), + TextDrawingComparer, img => { img.Mutate(c => c.DrawText(text, new Font(font, fontSize), color, new PointF(x, y))); }, - $"{fontName}-{fontSize}-{fnDisplayText}-({x},{y})", + $"{fontName}-{fontSize}-{ToTestOutputDisplayText(text)}-({x},{y})", appendPixelTypeToFileName: false, appendSourceFileOrDescription: true); } @@ -98,7 +98,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text TPixel color = NamedColors.Black; provider.VerifyOperation( - ImageComparer.Tolerant(imageThreshold: 0.1f, perPixelManhattanThreshold: 20), + TextDrawingComparer, img => { img.Mutate(c => c.DrawText(textOptions, sb.ToString(), font, color, new PointF(10, 5))); @@ -121,17 +121,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( - ImageComparer.Tolerant(imageThreshold: 0.1f, perPixelManhattanThreshold: 20), + TextDrawingComparer, img => { img.Mutate(c => c.DrawText(text, new Font(font, fontSize), null, Pens.Solid(color, 1), new PointF(x, y))); }, - $"pen_{fontName}-{fontSize}-{fnDisplayText}-({x},{y})", + $"pen_{fontName}-{fontSize}-{ToTestOutputDisplayText(text)}-({x},{y})", appendPixelTypeToFileName: false, appendSourceFileOrDescription: true); } @@ -153,7 +151,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text TPixel color = NamedColors.Black; provider.VerifyOperation( - ImageComparer.Tolerant(imageThreshold: 0.1f, perPixelManhattanThreshold: 20), + TextDrawingComparer, img => { img.Mutate(c => c.DrawText(text, new Font(font, fontSize), null, Pens.DashDot(color, 3), new PointF(x, y))); @@ -180,7 +178,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text IPen outlinePen = Pens.DashDot(colorOutline, 3); provider.VerifyOperation( - ImageComparer.Tolerant(imageThreshold: 0.1f, perPixelManhattanThreshold: 20), + TextDrawingComparer, img => { IPath path = new Path(new LinearLineSegment(new Point(0, img.Height), new Point(img.Width, 0))); @@ -214,13 +212,12 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text string text) where TPixel : struct, IPixel { - Font font = CreateFont(fontName, fontSize); TPixel colorFill = NamedColors.Black; IBrush fillBrush = Brushes.Solid(colorFill); provider.VerifyOperation( - ImageComparer.Tolerant(imageThreshold: 0.1f, perPixelManhattanThreshold: 20), + TextDrawingComparer, img => { int w = (int)(img.Width * 0.6); diff --git a/tests/Images/External b/tests/Images/External index 83f6cbab9..0e6407be7 160000 --- a/tests/Images/External +++ b/tests/Images/External @@ -1 +1 @@ -Subproject commit 83f6cbab9a08b550c84bf931c95188341140516a +Subproject commit 0e6407be7081341526f815a4d70e7912db276a98 From 38ba1f2dfc5c55e8f815e1d3c4bcbc44bdfecf73 Mon Sep 17 00:00:00 2001 From: Anton Firszov Date: Sun, 17 Jun 2018 16:41:37 +0200 Subject: [PATCH 14/21] fix build after merge --- .../Processing/Text/Processors/DrawTextProcessor.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs index d00cba8a3..0d534dc39 100644 --- a/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs +++ b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs @@ -118,7 +118,7 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors { foreach (DrawingOperation operation in operations) { - IBuffer2D buffer = operation.Map; + Buffer2D buffer = operation.Map; int startY = operation.Location.Y; int startX = operation.Location.X; int offSetSpan = 0; @@ -153,7 +153,7 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors private struct DrawingOperation { - public IBuffer2D Map { get; set; } + public Buffer2D Map { get; set; } public Point Location { get; set; } } From 36298f43e7b6c6f6cbb12fb06bda2a63e709144a Mon Sep 17 00:00:00 2001 From: Anton Firszov Date: Sun, 17 Jun 2018 16:48:06 +0200 Subject: [PATCH 15/21] fine tune tolerance --- .../Drawing/Text/DrawTextOnImageTests.cs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs b/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs index ef6dc40f0..abb384ffb 100644 --- a/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs +++ b/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs @@ -31,10 +31,8 @@ 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)] @@ -124,7 +122,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text TPixel color = NamedColors.Black; provider.VerifyOperation( - TextDrawingComparer, + OutlinedTextDrawingComparer, img => { img.Mutate(c => c.DrawText(text, new Font(font, fontSize), null, Pens.Solid(color, 1), new PointF(x, y))); @@ -151,7 +149,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text TPixel color = NamedColors.Black; provider.VerifyOperation( - TextDrawingComparer, + OutlinedTextDrawingComparer, img => { img.Mutate(c => c.DrawText(text, new Font(font, fontSize), null, Pens.DashDot(color, 3), new PointF(x, y))); @@ -178,7 +176,7 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text IPen outlinePen = Pens.DashDot(colorOutline, 3); provider.VerifyOperation( - TextDrawingComparer, + OutlinedTextDrawingComparer, img => { IPath path = new Path(new LinearLineSegment(new Point(0, img.Height), new Point(img.Width, 0))); From 717bf96d555858dac2cd1f0e64f53f70a25715ea Mon Sep 17 00:00:00 2001 From: Scott Williams Date: Sun, 17 Jun 2018 21:07:53 +0100 Subject: [PATCH 16/21] drop resolved todo comment --- src/ImageSharp.Drawing/Primitives/ShapePath.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/ImageSharp.Drawing/Primitives/ShapePath.cs b/src/ImageSharp.Drawing/Primitives/ShapePath.cs index 7aae2bf8e..7a8c9e895 100644 --- a/src/ImageSharp.Drawing/Primitives/ShapePath.cs +++ b/src/ImageSharp.Drawing/Primitives/ShapePath.cs @@ -16,7 +16,6 @@ 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)) { From c13fb2cd1d8733430474a3829c1b8428bb2d9cd6 Mon Sep 17 00:00:00 2001 From: Scott Williams Date: Sun, 17 Jun 2018 21:11:37 +0100 Subject: [PATCH 17/21] make processors immutable again --- .../Drawing/Processors/FillRegionProcessor.cs | 19 +-- .../Text/Processors/DrawTextProcessor.cs | 35 +++-- .../OldProcessors/DrawTextProcessorV1.cs | 138 ------------------ 3 files changed, 27 insertions(+), 165 deletions(-) delete mode 100644 tests/ImageSharp.Benchmarks/Drawing/OldProcessors/DrawTextProcessorV1.cs diff --git a/src/ImageSharp.Drawing/Processing/Drawing/Processors/FillRegionProcessor.cs b/src/ImageSharp.Drawing/Processing/Drawing/Processors/FillRegionProcessor.cs index 598e696ba..c81f4028b 100644 --- a/src/ImageSharp.Drawing/Processing/Drawing/Processors/FillRegionProcessor.cs +++ b/src/ImageSharp.Drawing/Processing/Drawing/Processors/FillRegionProcessor.cs @@ -37,29 +37,22 @@ namespace SixLabors.ImageSharp.Processing.Drawing.Processors } /// - /// Initializes a new instance of the class. - /// - public FillRegionProcessor() - { - } - - /// - /// Gets or sets the brush. + /// Gets the brush. /// - public IBrush Brush { get; set; } + public IBrush Brush { get; } /// - /// Gets or sets the region that this processor applies to. + /// Gets the region that this processor applies to. /// - public Region Region { get; set; } + public Region Region { get; } /// - /// Gets or sets the options. + /// Gets the options. /// /// /// The options. /// - public GraphicsOptions Options { get; set; } + public GraphicsOptions Options { get; } /// protected override void OnFrameApply(ImageFrame source, Rectangle sourceRectangle, Configuration configuration) diff --git a/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs index 0d534dc39..f6a66b566 100644 --- a/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs +++ b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs @@ -39,43 +39,50 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors /// 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) { - this.Brush = brush; + 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.Pen = pen; this.Font = font; this.Location = location; + this.Brush = brush; + this.Pen = pen; } /// - /// Gets or sets the brush. + /// Gets the brush. /// - public IBrush Brush { get; set; } + public IBrush Brush { get; } /// - /// Gets or sets the options + /// Gets the options /// - public TextGraphicsOptions Options { get; set; } + public TextGraphicsOptions Options { get; } /// - /// Gets or sets the text + /// Gets the text /// - public string Text { get; set; } + public string Text { get; } /// - /// Gets or sets the pen used for outlining the text, if Null then we will not outline + /// Gets the pen used for outlining the text, if Null then we will not outline /// - public IPen Pen { get; set; } + public IPen Pen { get; } /// - /// Gets or sets the font used to render the text. + /// Gets the font used to render the text. /// - public Font Font { get; set; } + public Font Font { get; } /// - /// Gets or sets the location to draw the text at. + /// Gets the location to draw the text at. /// - public PointF Location { get; set; } + public PointF Location { get; } protected override void BeforeImageApply(Image source, Rectangle sourceRectangle) { diff --git a/tests/ImageSharp.Benchmarks/Drawing/OldProcessors/DrawTextProcessorV1.cs b/tests/ImageSharp.Benchmarks/Drawing/OldProcessors/DrawTextProcessorV1.cs deleted file mode 100644 index 3faaec2c2..000000000 --- a/tests/ImageSharp.Benchmarks/Drawing/OldProcessors/DrawTextProcessorV1.cs +++ /dev/null @@ -1,138 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using SixLabors.Fonts; -using SixLabors.ImageSharp.PixelFormats; -using SixLabors.ImageSharp.Primitives; -using SixLabors.ImageSharp.Processing.Drawing.Brushes; -using SixLabors.ImageSharp.Processing.Drawing.Pens; -using SixLabors.ImageSharp.Processing.Drawing.Processors; -using SixLabors.ImageSharp.Processing.Processors; -using SixLabors.ImageSharp.Processing.Text; -using SixLabors.Primitives; -using SixLabors.Shapes; - -namespace SixLabors.ImageSharp.Benchmarks.Drawing.OldProcessors -{ - - /// - /// 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 FillRegionProcessor fillRegionProcessor = null; - - /// - /// 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) - { - this.Brush = brush; - this.Options = options; - this.Text = text; - this.Pen = pen; - this.Font = font; - this.Location = location; - } - - /// - /// Gets or sets the brush. - /// - public IBrush Brush { get; set; } - - /// - /// Gets or sets the options - /// - public TextGraphicsOptions Options { get; set; } - - /// - /// Gets or sets the text - /// - public string Text { get; set; } - - /// - /// Gets or sets the pen used for outlining the text, if Null then we will not outline - /// - public IPen Pen { get; set; } - - /// - /// Gets or sets the font used to render the text. - /// - public Font Font { get; set; } - - /// - /// Gets or sets the location to draw the text at. - /// - public PointF Location { get; set; } - - 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 - }; - - IPathCollection glyphs = TextBuilder.GenerateGlyphs(this.Text, style); - - var pathOptions = (GraphicsOptions)this.Options; - if (this.Brush != null) - { - // we will reuse the processor for all fill operations to reduce allocations - if (this.fillRegionProcessor == null) - { - this.fillRegionProcessor = new FillRegionProcessor() - { - Brush = this.Brush, - Options = pathOptions - }; - } - - foreach (IPath p in glyphs) - { - this.fillRegionProcessor.Region = new ShapeRegion(p); - this.fillRegionProcessor.Apply(source, sourceRectangle); - } - } - - if (this.Pen != null) - { - // we will reuse the processor for all fill operations to reduce allocations - if (this.fillRegionProcessor == null) - { - this.fillRegionProcessor = new FillRegionProcessor() - { - Brush = this.Brush, - Options = pathOptions - }; - } - - foreach (IPath p in glyphs) - { - this.fillRegionProcessor.Region = new ShapePath(p, this.Pen); - this.fillRegionProcessor.Apply(source, sourceRectangle); - } - } - } - - /// - 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 - } - } -} From 948ea7e80b5f588c0893834b4464e051b7db46a3 Mon Sep 17 00:00:00 2001 From: Scott Williams Date: Sun, 17 Jun 2018 21:13:47 +0100 Subject: [PATCH 18/21] remove draw text along path --- .../Text/DrawTextExtensions.Path.cs | 199 ------------------ .../Processors/DrawTextOnPathProcessor.cs | 123 ----------- .../Drawing/Text/DrawText.Path.cs | 179 ---------------- .../Drawing/Text/DrawTextOnImageTests.cs | 82 -------- 4 files changed, 583 deletions(-) delete mode 100644 src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.Path.cs delete mode 100644 src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextOnPathProcessor.cs delete mode 100644 tests/ImageSharp.Tests/Drawing/Text/DrawText.Path.cs 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 827d6b95f..000000000 --- a/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.Path.cs +++ /dev/null @@ -1,199 +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.ImageSharp.Processing.Text.Processors; -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 => - source.ApplyProcessor(new DrawTextOnPathProcessor(options, text, font, brush, pen, path)); - } -} \ No newline at end of file diff --git a/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextOnPathProcessor.cs b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextOnPathProcessor.cs deleted file mode 100644 index 1e703d1cc..000000000 --- a/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextOnPathProcessor.cs +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright (c) Six Labors and contributors. -// Licensed under the Apache License, Version 2.0. - -using System; -using System.Threading.Tasks; -using SixLabors.Fonts; -using SixLabors.ImageSharp.PixelFormats; -using SixLabors.ImageSharp.Primitives; -using SixLabors.ImageSharp.Processing.Drawing.Brushes; -using SixLabors.ImageSharp.Processing.Drawing.Pens; -using SixLabors.ImageSharp.Processing.Drawing.Processors; -using SixLabors.ImageSharp.Processing.Processors; -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 DrawTextOnPathProcessor : ImageProcessor - where TPixel : struct, IPixel - { - private FillRegionProcessor fillRegionProcessor = null; - - /// - /// 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 path on which to draw the text along. - public DrawTextOnPathProcessor(TextGraphicsOptions options, string text, Font font, IBrush brush, IPen pen, IPath path) - { - this.Brush = brush; - this.Options = options; - this.Text = text; - this.Pen = pen; - this.Font = font; - this.Path = path; - } - - /// - /// Gets or sets the brush. - /// - public IBrush Brush { get; set; } - - /// - /// Gets or sets the options - /// - private TextGraphicsOptions Options { get; set; } - - /// - /// Gets or sets the text - /// - private string Text { get; set; } - - /// - /// Gets or sets the pen used for outlining the text, if Null then we will not outline - /// - public IPen Pen { get; set; } - - /// - /// Gets or sets the font used to render the text. - /// - public Font Font { get; set; } - - /// - /// Gets or sets the path to draw the text along. - /// - public IPath Path { get; set; } - - 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) - { - ApplyKerning = this.Options.ApplyKerning, - TabWidth = this.Options.TabWidth, - WrappingWidth = this.Path.Length, - HorizontalAlignment = this.Options.HorizontalAlignment, - VerticalAlignment = this.Options.VerticalAlignment - }; - - IPathCollection glyphs = TextBuilder.GenerateGlyphs(this.Text, this.Path, style); - this.fillRegionProcessor = new FillRegionProcessor(); - this.fillRegionProcessor.Options = (GraphicsOptions)this.Options; - - if (this.Brush != null) - { - this.fillRegionProcessor.Brush = this.Brush; - - foreach (IPath p in glyphs) - { - this.fillRegionProcessor.Region = new ShapeRegion(p); - this.fillRegionProcessor.Apply(source, sourceRectangle); - } - } - - if (this.Pen != null) - { - this.fillRegionProcessor.Brush = this.Pen.StrokeFill; - - foreach (IPath p in glyphs) - { - this.fillRegionProcessor.Region = new ShapePath(p, this.Pen); - this.fillRegionProcessor.Apply(source, sourceRectangle); - } - } - } - - /// - 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 - } - } -} \ No newline at end of file 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 d352489b8..000000000 --- a/tests/ImageSharp.Tests/Drawing/Text/DrawText.Path.cs +++ /dev/null @@ -1,179 +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.ImageSharp.Processing.Text.Processors; -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); - } - - [Fact] - public void FillsForEachACharachterWhenBrushSetAndNotPenDefaultOptions() - { - this.operations.DrawText("123", this.Font, Brushes.Solid(Rgba32.Red), null, this.path); - - this.Verify>(0); - } - - [Fact] - public void FillsForEachACharachterWhenBrushSet() - { - this.operations.DrawText(new TextGraphicsOptions(true), "123", this.Font, Brushes.Solid(Rgba32.Red), this.path); - - this.Verify>(0); - } - - [Fact] - public void FillsForEachACharachterWhenBrushSetDefaultOptions() - { - this.operations.DrawText("123", this.Font, Brushes.Solid(Rgba32.Red), this.path); - - this.Verify>(0); - } - - [Fact] - public void FillsForEachACharachterWhenColorSet() - { - this.operations.DrawText(new TextGraphicsOptions(true), "123", this.Font, Rgba32.Red, this.path); - - var processor = this.Verify>(0); - - 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); - - DrawTextOnPathProcessor processor = this.Verify>(0); - - 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); - } - - [Fact] - public void DrawForEachACharachterWhenPenSetAndNotBrushDefaultOptions() - { - this.operations.DrawText("123", this.Font, null, Pens.Dash(Rgba32.Red, 1), this.path); - - var processor = this.Verify>(0); - } - - [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); - } - - [Fact] - public void DrawForEachACharachterWhenPenSetDefaultOptions() - { - this.operations.DrawText("123", this.Font, Pens.Dash(Rgba32.Red, 1), this.path); - - DrawTextOnPathProcessor processor = this.Verify>(0); - } - - [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); - } - - [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); - } - - [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); - } - - [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); - } - } -} diff --git a/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs b/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs index abb384ffb..3ceba0838 100644 --- a/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs +++ b/tests/ImageSharp.Tests/Drawing/Text/DrawTextOnImageTests.cs @@ -159,88 +159,6 @@ namespace SixLabors.ImageSharp.Tests.Drawing.Text appendSourceFileOrDescription: true); } - [Theory] - [WithSolidFilledImages(200, 100, "White", PixelTypes.Rgba32, 50, "SixLaborsSampleAB.woff", AB)] - [WithSolidFilledImages(900, 100, "White", PixelTypes.Rgba32, 50, "OpenSans-Regular.ttf", TestText)] - public void FontShapesAreRenderedCorrectlyAlongAPath( - TestImageProvider provider, - int fontSize, - string fontName, - string text) - where TPixel : struct, IPixel - { - Font font = CreateFont(fontName, fontSize); - TPixel colorFill = NamedColors.Gray; - TPixel colorOutline = NamedColors.Black; - IBrush fillBrush = Brushes.Solid(colorFill); - IPen outlinePen = Pens.DashDot(colorOutline, 3); - - provider.VerifyOperation( - OutlinedTextDrawingComparer, - img => - { - IPath path = new Path(new LinearLineSegment(new Point(0, img.Height), new Point(img.Width, 0))); - img.Mutate( - c => - { - c.DrawText( - new TextGraphicsOptions - { - HorizontalAlignment = HorizontalAlignment.Center, - VerticalAlignment = VerticalAlignment.Top - }, - text, - new Font(font, fontSize), - fillBrush, - outlinePen, - path); - }); - }, - $"pen_{fontName}-{fontSize}-{ToTestOutputDisplayText(text)}", - appendPixelTypeToFileName: false, - appendSourceFileOrDescription: true); - } - - [Theory] - [WithSolidFilledImages(600, 600, "White", PixelTypes.Rgba32, 50, "OpenSans-Regular.ttf", TestText)] - public void FontShapesAreRenderedCorrectlyAlongACirclePath( - TestImageProvider provider, - int fontSize, - string fontName, - string text) - where TPixel : struct, IPixel - { - Font font = CreateFont(fontName, fontSize); - TPixel colorFill = NamedColors.Black; - IBrush fillBrush = Brushes.Solid(colorFill); - - provider.VerifyOperation( - TextDrawingComparer, - img => - { - int w = (int)(img.Width * 0.6); - int h = (int)(img.Height * 0.6); - IPath path = new EllipsePolygon(img.Width/2, img.Height/2, w, h); - - img.Mutate(c => - { - c.DrawText( - new TextGraphicsOptions - { - HorizontalAlignment = HorizontalAlignment.Center, - VerticalAlignment = VerticalAlignment.Top - }, - text, - new Font(font, fontSize), - fillBrush, - path); - }); - }, - $"pen_{fontName}-{fontSize}-{ToTestOutputDisplayText(text)}", - appendPixelTypeToFileName: false, - appendSourceFileOrDescription: true); - } - private static string Repeat(string str, int times) => string.Concat(Enumerable.Repeat(str, times)); private static string ToTestOutputDisplayText(string text) From b270cbbc6d4e08d4e8d2b96630271f3da350af94 Mon Sep 17 00:00:00 2001 From: Scott Williams Date: Mon, 18 Jun 2018 19:28:44 +0100 Subject: [PATCH 19/21] drop the Shapes.Text dependency --- .../ImageSharp.Drawing.csproj | 3 ++- .../Text/Processors/DrawTextProcessor.cs | 24 +++++++++---------- .../ImageSharp.Benchmarks.csproj | 1 + 3 files changed, 15 insertions(+), 13 deletions(-) diff --git a/src/ImageSharp.Drawing/ImageSharp.Drawing.csproj b/src/ImageSharp.Drawing/ImageSharp.Drawing.csproj index 3776830ae..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/Processing/Text/Processors/DrawTextProcessor.cs b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs index f6a66b566..a38a0c320 100644 --- a/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs +++ b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs @@ -169,13 +169,13 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors { private PathBuilder builder; - private Point currentRenderPosition = default(Point); - private int currentRenderingGlyph = 0; + private Point currentRenderPosition = default; + private GlyphRendererParameters currentRenderingGlyph = default; private int offset = 0; private PointF currentPoint = default(PointF); - private HashSet renderedGlyphs = new HashSet(); - private Dictionary> glyphMap; - private Dictionary> glyphMapPen; + private HashSet renderedGlyphs = new HashSet(); + private Dictionary> glyphMap; + private Dictionary> glyphMapPen; private bool renderOutline = false; private bool renderFill = false; private bool raterizationRequired = false; @@ -190,14 +190,14 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors if (this.renderFill) { this.FillOperations = new List(size); - this.glyphMap = new Dictionary>(); + this.glyphMap = new Dictionary>(); } if (this.renderOutline) { this.offset = (int)MathF.Ceiling((pen.StrokeWidth * 2) + 2); this.OutlineOperations = new List(size); - this.glyphMapPen = new Dictionary>(); + this.glyphMapPen = new Dictionary>(); } this.builder = new PathBuilder(); @@ -218,14 +218,14 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors this.builder.StartFigure(); } - public bool BeginGlyph(RectangleF bounds, int cacheKey) + 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.currentRenderingGlyph = cacheKey; - if (this.renderedGlyphs.Contains(cacheKey)) + this.currentRenderingGlyph = paramters; + if (this.renderedGlyphs.Contains(paramters)) { // we have already drawn the glyph vectors skip trying again this.raterizationRequired = false; @@ -259,7 +259,7 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors { if (this.renderFill) { - foreach (KeyValuePair> m in this.glyphMap) + foreach (KeyValuePair> m in this.glyphMap) { m.Value.Dispose(); } @@ -267,7 +267,7 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors if (this.renderOutline) { - foreach (KeyValuePair> m in this.glyphMapPen) + foreach (KeyValuePair> m in this.glyphMapPen) { m.Value.Dispose(); } 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 @@ + From ecf160e5bbde7d16fa8af8d29dc25ace5529dd9b Mon Sep 17 00:00:00 2001 From: Anton Firszov Date: Mon, 18 Jun 2018 23:28:54 +0200 Subject: [PATCH 20/21] refactor QuickSort to a common utility class --- .../Drawing/Processors/FillRegionProcessor.cs | 69 +-------------- .../Processing/Text/DrawTextExtensions.cs | 2 - .../Text/Processors/DrawTextProcessor.cs | 58 +------------ src/ImageSharp.Drawing/Utils/QuickSort.cs | 84 +++++++++++++++++++ .../ImageSharp.Tests/Drawing/BeziersTests.cs | 3 +- .../Drawing/Utils/QuickSortTests.cs | 51 +++++++++++ 6 files changed, 140 insertions(+), 127 deletions(-) create mode 100644 src/ImageSharp.Drawing/Utils/QuickSort.cs create mode 100644 tests/ImageSharp.Tests/Drawing/Utils/QuickSortTests.cs 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.cs b/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.cs index ed7a7bbfa..a20d7f730 100644 --- a/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.cs +++ b/src/ImageSharp.Drawing/Processing/Text/DrawTextExtensions.cs @@ -3,12 +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 { diff --git a/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs index a38a0c320..f86bd827f 100644 --- a/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs +++ b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs @@ -3,16 +3,13 @@ using System; using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Threading.Tasks; using SixLabors.Fonts; using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.PixelFormats; -using SixLabors.ImageSharp.Primitives; using SixLabors.ImageSharp.Processing.Drawing.Brushes; using SixLabors.ImageSharp.Processing.Drawing.Pens; -using SixLabors.ImageSharp.Processing.Drawing.Processors; using SixLabors.ImageSharp.Processing.Processors; +using SixLabors.ImageSharp.Utils; using SixLabors.Memory; using SixLabors.Primitives; using SixLabors.Shapes; @@ -377,7 +374,7 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors buffer[i] = intersectionSpan[i].X; } - QuickSort(buffer.Slice(0, pointsFound)); + QuickSort.Sort(buffer.Slice(0, pointsFound)); for (int point = 0; point < pointsFound; point += 2) { @@ -439,57 +436,6 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors return fullBuffer; } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void Swap(Span data, int left, int right) - { - float tmp = data[left]; - data[left] = data[right]; - data[right] = tmp; - } - - private static void QuickSort(Span data) - { - QuickSort(data, 0, data.Length - 1); - } - - private static void QuickSort(Span data, int lo, int hi) - { - if (lo < hi) - { - int p = Partition(data, lo, hi); - QuickSort(data, lo, p); - QuickSort(data, p + 1, hi); - } - } - - private static int Partition(Span data, int lo, int hi) - { - float pivot = data[lo]; - int i = lo - 1; - int j = hi + 1; - while (true) - { - do - { - i = i + 1; - } - while (data[i] < pivot && i < hi); - - do - { - j = j - 1; - } - while (data[j] > pivot && j > lo); - - if (i >= j) - { - return j; - } - - Swap(data, i, j); - } - } - public void EndText() { } 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.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/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 From bd65fc543cd38ea48afc508d4f60c6bc6df5ef56 Mon Sep 17 00:00:00 2001 From: Anton Firszov Date: Mon, 18 Jun 2018 23:50:41 +0200 Subject: [PATCH 21/21] CachingGlyphRenderer: use a 1 dictionary instead of 3 --- .../Text/Processors/DrawTextProcessor.cs | 71 +++++++++++-------- 1 file changed, 40 insertions(+), 31 deletions(-) diff --git a/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs index f86bd827f..9327f9449 100644 --- a/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs +++ b/src/ImageSharp.Drawing/Processing/Text/Processors/DrawTextProcessor.cs @@ -167,19 +167,19 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors private PathBuilder builder; private Point currentRenderPosition = default; - private GlyphRendererParameters currentRenderingGlyph = default; + private GlyphRendererParameters currentGlyphRenderParams = default; private int offset = 0; private PointF currentPoint = default(PointF); - private HashSet renderedGlyphs = new HashSet(); - private Dictionary> glyphMap; - private Dictionary> glyphMapPen; + + private readonly Dictionary glyphData = new Dictionary(); + private bool renderOutline = false; private bool renderFill = false; private bool raterizationRequired = false; - public CachingGlyphRenderer(MemoryAllocator memoryManager, int size, IPen pen, bool renderFill) + public CachingGlyphRenderer(MemoryAllocator memoryAllocator, int size, IPen pen, bool renderFill) { - this.MemoryManager = memoryManager; + this.MemoryAllocator = memoryAllocator; this.Pen = pen; this.renderFill = renderFill; this.renderOutline = pen != null; @@ -187,14 +187,12 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors if (this.renderFill) { this.FillOperations = new List(size); - this.glyphMap = new Dictionary>(); } if (this.renderOutline) { this.offset = (int)MathF.Ceiling((pen.StrokeWidth * 2) + 2); this.OutlineOperations = new List(size); - this.glyphMapPen = new Dictionary>(); } this.builder = new PathBuilder(); @@ -204,7 +202,7 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors public List OutlineOperations { get; } - public MemoryAllocator MemoryManager { get; internal set; } + public MemoryAllocator MemoryAllocator { get; internal set; } public IPen Pen { get; internal set; } @@ -221,8 +219,8 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors // 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.currentRenderingGlyph = paramters; - if (this.renderedGlyphs.Contains(paramters)) + this.currentGlyphRenderParams = paramters; + if (this.glyphData.ContainsKey(paramters)) { // we have already drawn the glyph vectors skip trying again this.raterizationRequired = false; @@ -254,21 +252,12 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors public void Dispose() { - if (this.renderFill) + foreach (KeyValuePair kv in this.glyphData) { - foreach (KeyValuePair> m in this.glyphMap) - { - m.Value.Dispose(); - } + kv.Value.Dispose(); } - if (this.renderOutline) - { - foreach (KeyValuePair> m in this.glyphMapPen) - { - m.Value.Dispose(); - } - } + this.glyphData.Clear(); } public void EndFigure() @@ -278,13 +267,16 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors public void EndGlyph() { + GlyphRenderData renderData = default; + // has the glyoh been rendedered already???? if (this.raterizationRequired) { IPath path = this.builder.Build(); + if (this.renderFill) { - this.glyphMap[this.currentRenderingGlyph] = this.Render(path); + renderData.FillMap = this.Render(path); } if (this.renderOutline) @@ -298,10 +290,14 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors path = path.GenerateOutline(this.Pen.StrokeWidth, this.Pen.StrokePattern); } - this.glyphMapPen[this.currentRenderingGlyph] = this.Render(path); + renderData.OutlineMap = this.Render(path); } - this.renderedGlyphs.Add(this.currentRenderingGlyph); + this.glyphData[this.currentGlyphRenderParams] = renderData; + } + else + { + renderData = this.glyphData[this.currentGlyphRenderParams]; } if (this.renderFill) @@ -309,7 +305,7 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors this.FillOperations.Add(new DrawingOperation { Location = this.currentRenderPosition, - Map = this.glyphMap[this.currentRenderingGlyph] + Map = renderData.FillMap }); } @@ -318,7 +314,7 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors this.OutlineOperations.Add(new DrawingOperation { Location = this.currentRenderPosition, - Map = this.glyphMapPen[this.currentRenderingGlyph] + Map = renderData.OutlineMap }); } } @@ -341,10 +337,10 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors } // take the path inside the path builder, scan thing and generate a Buffer2d representing the glyph and cache it. - Buffer2D fullBuffer = this.MemoryManager.Allocate2D(size.Width + 1, size.Height + 1, true); + Buffer2D fullBuffer = this.MemoryAllocator.Allocate2D(size.Width + 1, size.Height + 1, true); - using (IBuffer bufferBacking = this.MemoryManager.Allocate(path.MaxIntersections)) - using (IBuffer rowIntersectionBuffer = this.MemoryManager.Allocate(size.Width)) + using (IBuffer bufferBacking = this.MemoryAllocator.Allocate(path.MaxIntersections)) + using (IBuffer rowIntersectionBuffer = this.MemoryAllocator.Allocate(size.Width)) { float subpixelFraction = 1f / subpixelCount; float subpixelFractionPoint = subpixelFraction / subpixelCount; @@ -457,6 +453,19 @@ namespace SixLabors.ImageSharp.Processing.Text.Processors 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