Skip to content

Commit 940220c

Browse files
Add ComputeLength extension
1 parent 3d87313 commit 940220c

3 files changed

Lines changed: 54 additions & 1 deletion

File tree

samples/DrawShapesWithImageSharp/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ private static void DrawText(string text, IPath path)
7777
var font = new Font(fam, 30);
7878
var style = new RendererOptions(font, 72)
7979
{
80-
WrappingWidth = path.Bounds.Width,
80+
WrappingWidth = path.ComputeLength(),
8181
VerticalAlignment = VerticalAlignment.Top,
8282
HorizontalAlignment = HorizontalAlignment.Center,
8383
};

src/ImageSharp.Drawing/Shapes/PathExtensions.cs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Copyright (c) Six Labors.
22
// Licensed under the Apache License, Version 2.0.
33

4+
using System;
45
using System.Numerics;
56

67
namespace SixLabors.ImageSharp.Drawing
@@ -121,5 +122,39 @@ public static IPath Scale(this IPath path, float scaleX, float scaleY)
121122
/// <returns>A <see cref="IPath"/> with a translate transform applied.</returns>
122123
public static IPath Scale(this IPath path, float scale)
123124
=> path.Transform(Matrix3x2.CreateScale(scale, RectangleF.Center(path.Bounds)));
125+
126+
/// <summary>
127+
/// Calculates the length of the path as though each segment were unrolled into a line.
128+
/// </summary>
129+
/// <param name="path">The path to compute the length for.</param>
130+
/// <returns>
131+
/// The <see cref="int"/> representing the unrolled length.
132+
/// For closed paths, the length includes an implicit closing segment.
133+
/// </returns>
134+
public static float ComputeLength(this IPath path)
135+
{
136+
float dist = 0;
137+
foreach (ISimplePath s in path.Flatten())
138+
{
139+
ReadOnlySpan<PointF> points = s.Points.Span;
140+
if (points.Length < 2)
141+
{
142+
// Only a single point
143+
continue;
144+
}
145+
146+
for (int i = 1; i < points.Length; i++)
147+
{
148+
dist += Vector2.Distance(points[i - 1], points[i]);
149+
}
150+
151+
if (s.IsClosed)
152+
{
153+
dist += Vector2.Distance(points[0], points[points.Length - 1]);
154+
}
155+
}
156+
157+
return dist;
158+
}
124159
}
125160
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// Copyright (c) Six Labors.
2+
// Licensed under the Apache License, Version 2.0.
3+
4+
using Xunit;
5+
6+
namespace SixLabors.ImageSharp.Drawing.Tests.Drawing.Paths
7+
{
8+
public class ComputeLength
9+
{
10+
[Fact]
11+
public void CanComputeUnrolledLength()
12+
{
13+
var polygon = new RectangularPolygon(PointF.Empty, new PointF(100, 200));
14+
15+
Assert.Equal(600, polygon.ComputeLength());
16+
}
17+
}
18+
}

0 commit comments

Comments
 (0)