geom/rectangle.go
Sander Schobers cc2addf7e2 Added RectRel{,F,F32} methods.
- Instead of a second coordinate (x,y) you can provide the width & height of the rectangle.
2020-05-15 10:24:09 +02:00

54 lines
1.3 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}}
}
// RectRel is a shorthand function to create a rectangle specifying its width and height instead of a second coordinate.
func RectRel(x, y, w, h int) Rectangle {
return Rectangle{Point{x, y}, Point{x + w, y + h}}
}
// 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},
}
}