From 980c6e23166ca57dc87fc41562591fd9096321e8 Mon Sep 17 00:00:00 2001 From: BobLd Date: Fri, 15 Jan 2021 11:20:45 +0000 Subject: [PATCH] Use Euclidean distance in PdfRectangle's width and height --- src/UglyToad.PdfPig.Core/PdfRectangle.cs | 11 ++++++++--- .../Geometry/PdfRectangleTests.cs | 12 ++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/UglyToad.PdfPig.Core/PdfRectangle.cs b/src/UglyToad.PdfPig.Core/PdfRectangle.cs index 41562c90..0888d45b 100644 --- a/src/UglyToad.PdfPig.Core/PdfRectangle.cs +++ b/src/UglyToad.PdfPig.Core/PdfRectangle.cs @@ -49,6 +49,7 @@ private double width; /// /// Width of the rectangle. + /// A positive number. /// public double Width { @@ -66,6 +67,7 @@ private double height; /// /// Height of the rectangle. + /// A positive number. /// public double Height { @@ -197,13 +199,16 @@ var cos = Math.Cos(t); var sin = Math.Sin(t); - var inverseRotation = new TransformationMatrix( + var inverseRotation = new TransformationMatrix( cos, -sin, 0, sin, cos, 0, 0, 0, 1); - width = inverseRotation.Transform(BottomRight).X - inverseRotation.Transform(BottomLeft).X; - height = inverseRotation.Transform(TopLeft).Y - inverseRotation.Transform(BottomLeft).Y; + // Using Abs as a proxy for Euclidean distance in 1D + // as it might happen that points have negative coordinates. + var bl = inverseRotation.Transform(BottomLeft); + width = Math.Abs(inverseRotation.Transform(BottomRight).X - bl.X); + height = Math.Abs(inverseRotation.Transform(TopLeft).Y - bl.Y); } /// diff --git a/src/UglyToad.PdfPig.Tests/Geometry/PdfRectangleTests.cs b/src/UglyToad.PdfPig.Tests/Geometry/PdfRectangleTests.cs index e3b5b873..ca2cb531 100644 --- a/src/UglyToad.PdfPig.Tests/Geometry/PdfRectangleTests.cs +++ b/src/UglyToad.PdfPig.Tests/Geometry/PdfRectangleTests.cs @@ -1682,5 +1682,17 @@ Assert.Equal(expected[2], rectR.TopLeft, PointComparer); Assert.Equal(expected[3], rectR.BottomLeft, PointComparer); } + + [Fact] + public void Issue261() + { + // Some points have negative coordinates after rotation, resulting in negative Height + PdfRectangle rect = new PdfRectangle(new PdfPoint(401.51, 461.803424), + new PdfPoint(300.17322363281249, 461.803424), + new PdfPoint(401.51, 291.45), + new PdfPoint(300.17322363281249, 291.45)); + + Assert.True(rect.Height > 0); + } } }