diff --git a/pointf32.go b/pointf32.go index 3fd0a87..716fdc2 100644 --- a/pointf32.go +++ b/pointf32.go @@ -5,6 +5,9 @@ type PointF32 struct { X, Y float32 } +// ZeroPtF32 is initialized on (0, 0). +var ZeroPtF32 = PointF32{X: 0, Y: 0} + // PtF32 is a shorthand function to create a point. func PtF32(x, y float32) PointF32 { return PointF32{x, y} diff --git a/rectanglef.go b/rectanglef.go index 29651d9..3461d21 100644 --- a/rectanglef.go +++ b/rectanglef.go @@ -55,6 +55,11 @@ func (r RectangleF) Dy() float64 { return r.Max.Y - r.Min.Y } +// Center returns the center of the rectangle. +func (r RectangleF) Center() PointF { + return PointF{r.Min.X + .5*(r.Max.X-r.Min.X), r.Min.Y + .5*(r.Max.Y-r.Min.Y)} +} + // Size returns the size of the rectangle. func (r RectangleF) Size() PointF { return PointF{r.Max.X - r.Min.X, r.Max.Y - r.Min.Y} diff --git a/rectanglef32.go b/rectanglef32.go new file mode 100644 index 0000000..8f4e756 --- /dev/null +++ b/rectanglef32.go @@ -0,0 +1,66 @@ +package geom + +// RectangleF32 is defined by two points, the minimum and maximum (floating point). +// Tries to use the same interface as the image. Rectangle but uses float32 instead of int. +type RectangleF32 struct { + Min, Max PointF32 +} + +// RectF32 is a shorthand function to create a rectangle. +func RectF32(x0, y0, x1, y1 float32) RectangleF32 { + if x0 > x1 { + x0, x1 = x1, x0 + } + if y0 > y1 { + y0, y1 = y1, y0 + } + return RectangleF32{PtF32(x0, y0), PtF32(x1, y1)} +} + +// Add translates rectangle r by point p. +func (r RectangleF32) Add(p PointF32) RectangleF32 { + return RectangleF32{ + PointF32{r.Min.X + p.X, r.Min.Y + p.Y}, + PointF32{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 RectangleF32) Inset(n float32) RectangleF32 { + 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 RectangleF32) Dx() float32 { + return r.Max.X - r.Min.X +} + +// Dy returns the height of r. +func (r RectangleF32) Dy() float32 { + return r.Max.Y - r.Min.Y +} + +// Center returns the center of the rectangle. +func (r RectangleF32) Center() PointF32 { + return PointF32{r.Min.X + .5*(r.Max.X-r.Min.X), r.Min.Y + .5*(r.Max.Y-r.Min.Y)} +} + +// Size returns the size of the rectangle. +func (r RectangleF32) Size() PointF32 { + return PointF32{r.Max.X - r.Min.X, r.Max.Y - r.Min.Y} +}