9fans.net/go@v0.0.5/draw/rectclip.go (about) 1 package draw 2 3 // RectClip attempts to clip *rp to be within b. 4 // If any of *rp overlaps b, RectClip modifies *rp to denote 5 // the overlapping portion and returns true. 6 // Otherwise, when *rp and b do not overlap, 7 // RectClip leaves *rp unmodified and returns false. 8 func RectClip(rp *Rectangle, b Rectangle) bool { 9 if !RectXRect(*rp, b) { 10 return false 11 } 12 13 if rp.Min.X < b.Min.X { 14 rp.Min.X = b.Min.X 15 } 16 if rp.Min.Y < b.Min.Y { 17 rp.Min.Y = b.Min.Y 18 } 19 if rp.Max.X > b.Max.X { 20 rp.Max.X = b.Max.X 21 } 22 if rp.Max.Y > b.Max.Y { 23 rp.Max.Y = b.Max.Y 24 } 25 return true 26 } 27 28 // RectXRect reports whether r and s cross, meaning they share any point 29 // or r is a zero-width or zero-height rectangle inside s. 30 // Note that the zero-sized cases make RectXRect(r, s) different from r.Overlaps(s). 31 func RectXRect(r, s Rectangle) bool { 32 return r.Min.X < s.Max.X && s.Min.X < r.Max.X && r.Min.Y < s.Max.Y && s.Min.Y < r.Max.Y 33 } 34 35 // RectInRect reports whether r is entirely contained in s. 36 // RectInRect(r, s) differs from r.In(s) 37 // in its handling of zero-width or zero-height rectangles. 38 func RectInRect(r, s Rectangle) bool { 39 return s.Min.X <= r.Min.X && r.Max.X <= s.Max.X && s.Min.Y <= r.Min.Y && r.Max.Y <= s.Max.Y 40 } 41 42 // CombineRect overwrites *r1 with the smallest rectangle 43 // enclosing both *r1 and r2. 44 // CombineRect(r1, r2) differs from *r1 = r1.Union(r2) 45 // in its handling of zero-width or zero-height rectangles. 46 func CombineRect(r1 *Rectangle, r2 Rectangle) { 47 if r1.Min.X > r2.Min.X { 48 r1.Min.X = r2.Min.X 49 } 50 if r1.Min.Y > r2.Min.Y { 51 r1.Min.Y = r2.Min.Y 52 } 53 if r1.Max.X < r2.Max.X { 54 r1.Max.X = r2.Max.X 55 } 56 if r1.Max.Y < r2.Max.Y { 57 r1.Max.Y = r2.Max.Y 58 } 59 }