geom/rectangle.go
Sander Schobers ac8c2029e4 Defined Rectangle in package.
- Instead of deriving from image.Rectangle.
Added methods on Rectangle.
2019-12-27 21:17:06 +01:00

49 lines
1.1 KiB
Go

package geom
// Rectangle represents a 2-dimensional surface with as boundaries Min (inclusive) and Max (exclusive).
type Rectangle struct {
Min, Max Point
}
// Rect is a shorthand function to create a rectangle.
func Rect(x0, y0, x1, y1 int) Rectangle {
if x0 > x1 {
x0, x1 = x1, x0
}
if y0 > y1 {
y0, y1 = y1, y0
}
return Rectangle{Point{x0, y0}, Point{x1, y1}}
}
// Add translates rectangle r by point p.
func (r Rectangle) Add(p Point) Rectangle {
return Rectangle{
Point{r.Min.X + p.X, r.Min.Y + p.Y},
Point{r.Max.X + p.X, r.Max.Y + p.Y},
}
}
// Dx returns the width of r.
func (r Rectangle) Dx() int {
return r.Max.X - r.Min.X
}
// Dy returns the height of r.
func (r Rectangle) Dy() int {
return r.Max.Y - r.Min.Y
}
// Size returns the size of the rectangle.
func (r Rectangle) Size() Point {
return Point{r.Max.X - r.Min.X, r.Max.Y - r.Min.Y}
}
// Sub translates rectangle r in the opposite direction of point p.
func (r Rectangle) Sub(p Point) Rectangle {
return Rectangle{
Point{r.Min.X - p.X, r.Min.Y - p.Y},
Point{r.Max.X - p.X, r.Max.Y - p.Y},
}
}