From 20f0bf7b1f672bf6203b420e247e45404c258d58 Mon Sep 17 00:00:00 2001 From: Sander Schobers Date: Mon, 6 Nov 2017 20:24:19 +0100 Subject: [PATCH] Added Inset and Add method to RectangleF --- rectanglef.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/rectanglef.go b/rectanglef.go index 734194e..29651d9 100644 --- a/rectanglef.go +++ b/rectanglef.go @@ -1,6 +1,7 @@ package geom // RectangleF is defined by two points, the minimum and maximum (floating point). +// Tries to use the same interface as the image.Rectangle but uses float64 instead of int. type RectangleF struct { Min, Max PointF } @@ -16,6 +17,34 @@ func RectF(x0, y0, x1, y1 float64) RectangleF { return RectangleF{PtF(x0, y0), PtF(x1, y1)} } +// Add translates rectangle r by point p. +func (r RectangleF) Add(p PointF) RectangleF { + return RectangleF{ + PointF{r.Min.X + p.X, r.Min.Y + p.Y}, + PointF{r.Max.X + p.X, r.Max.Y + p.Y}, + } +} + +// Inset returns the rectangle r inset by n. The resulting rectangle will never have +// a negative size. +func (r RectangleF) Inset(n float64) RectangleF { + if r.Dx() < 2*n { + r.Min.X = (r.Min.X + r.Max.X) / 2 + r.Max.X = r.Min.X + } else { + r.Min.X += n + r.Max.X -= n + } + if r.Dy() < 2*n { + r.Min.Y = (r.Min.Y + r.Max.Y) / 2 + r.Max.Y = r.Min.Y + } else { + r.Min.Y += n + r.Max.Y -= n + } + return r +} + // Dx returns the width of r. func (r RectangleF) Dx() float64 { return r.Max.X - r.Min.X