Skip to content

Commit 5a67308

Browse files
committed
Intersect.LineSegmentToLineSegment
1 parent f69c843 commit 5a67308

2 files changed

Lines changed: 60 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Copyright (c) Six Labors.
2+
// Licensed under the Apache License, Version 2.0.
3+
4+
namespace SixLabors.ImageSharp.Drawing.Utilities
5+
{
6+
internal static class Intersect
7+
{
8+
public static bool LineSegmentToLineSegment(PointF a0, PointF a1, PointF b0, PointF b1, ref PointF intersectionPoint)
9+
{
10+
float dax = a1.X - a0.X;
11+
float day = a1.Y - a0.Y;
12+
float dbx = b1.X - b0.X;
13+
float dby = b1.Y - b0.Y;
14+
15+
float s = ((-day * (a0.X - b0.X)) + (dax * (a0.Y - b0.Y))) / ((-dbx * day) + (dax * dby));
16+
float t = ((dbx * (a0.Y - b0.Y)) - (dby * (a0.X - b0.X))) / ((-dbx * day) + (dax * dby));
17+
18+
if (s >= 0 && s <= 1 && t >= 0 && t <= 1)
19+
{
20+
intersectionPoint.X = a0.X + (t * dax);
21+
intersectionPoint.Y = a0.Y + (t * day);
22+
return true;
23+
}
24+
25+
return false;
26+
}
27+
}
28+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Copyright (c) Six Labors.
2+
// Licensed under the Apache License, Version 2.0.
3+
4+
using SixLabors.ImageSharp.Drawing.Utilities;
5+
using Xunit;
6+
7+
namespace SixLabors.ImageSharp.Drawing.Tests.Drawing.Utils
8+
{
9+
public class IntersectTests
10+
{
11+
public static TheoryData<PointF, PointF, PointF, PointF, PointF?> LineSegmentToLineSegment_Data =
12+
new TheoryData<PointF, PointF, PointF, PointF, PointF?>()
13+
{
14+
{ new PointF(0, 0), new PointF(2, 3), new PointF(1, 3), new PointF(1, 0), new PointF(1, 1.5f) },
15+
{ new PointF(0, 0), new PointF(2, 3), new PointF(1, 3), new PointF(1, 2), null },
16+
};
17+
18+
[Theory]
19+
[MemberData(nameof(LineSegmentToLineSegment_Data))]
20+
public void LineSegmentToLineSegment(PointF a0, PointF a1, PointF b0, PointF b1, PointF? expected)
21+
{
22+
PointF ip = default;
23+
24+
bool result = Intersect.LineSegmentToLineSegment(a0, a1, b0, b1, ref ip);
25+
Assert.Equal(result, expected.HasValue);
26+
if (expected.HasValue)
27+
{
28+
Assert.Equal(expected.Value, ip);
29+
}
30+
}
31+
}
32+
}

0 commit comments

Comments
 (0)