Class: PerfectShape::Rectangle

Inherits:
Shape
  • Object
show all
Includes:
RectangularShape
Defined in:
lib/perfect_shape/rectangle.rb

Direct Known Subclasses

Square

Constant Summary collapse

OUT_LEFT =

bitmask indicating a point lies to the left

1
OUT_TOP =

bitmask indicating a point lies above

2
OUT_RIGHT =

bitmask indicating a point lies to the right

4
OUT_BOTTOM =

bitmask indicating a point lies below

8

Instance Attribute Summary

Attributes included from RectangularShape

#height, #width

Attributes included from PointLocation

#x, #y

Instance Method Summary collapse

Methods included from RectangularShape

#initialize, #max_x, #max_y

Methods included from PointLocation

#initialize, #min_x, #min_y

Methods inherited from Shape

#==, #bounding_box, #center_point, #center_x, #center_y, #height, #max_x, #max_y, #min_x, #min_y, #width

Instance Method Details

#contain?(x_or_point, y = nil, outline: false, distance_tolerance: 0) ⇒ @code true

Checks if rectangle contains point (two-number Array or x, y args)

the rectangle, false if the point lies outside of the rectangle’s bounds.

Parameters:

  • x

    The X coordinate of the point to test.

  • y (defaults to: nil)

    The Y coordinate of the point to test.

Returns:

  • (@code true)

    if the point lies within the bound of



52
53
54
55
56
57
58
59
60
61
# File 'lib/perfect_shape/rectangle.rb', line 52

def contain?(x_or_point, y = nil, outline: false, distance_tolerance: 0)
  x, y = Point.normalize_point(x_or_point, y)
  return unless x && y
  
  if outline
    edges.any? { |edge| edge.contain?(x, y, distance_tolerance: distance_tolerance) }
  else
    x.between?(self.x, self.x + width) && y.between?(self.y, self.y + height)
  end
end

#edgesObject



63
64
65
66
67
68
69
70
# File 'lib/perfect_shape/rectangle.rb', line 63

def edges
  [
    Line.new(points: [[self.x, self.y], [self.x + width, self.y]]),
    Line.new(points: [[self.x + width, self.y], [self.x + width, self.y + height]]),
    Line.new(points: [[self.x + width, self.y + height], [self.x, self.y + height]]),
    Line.new(points: [[self.x, self.y + height], [self.x, self.y]])
  ]
end

#out_state(x_or_point, y = nil) ⇒ Object

Returns out state for specified point (x,y): (left, right, top, bottom)

It can be 0 meaning not outside the rectangle, or if outside the rectangle, then a bit mask combination of OUT_LEFT, OUT_RIGHT, OUT_TOP, or OUT_BOTTOM



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/perfect_shape/rectangle.rb', line 77

def out_state(x_or_point, y = nil)
  x, y = Point.normalize_point(x_or_point, y)
  return unless x && y
  
  out = 0
  if self.width <= 0
      out |= OUT_LEFT | OUT_RIGHT
  elsif x < self.x
      out |= OUT_LEFT
  elsif x > self.x + self.width
      out |= OUT_RIGHT
  end
  if self.height <= 0
      out |= OUT_TOP | OUT_BOTTOM
  elsif y < self.y
      out |= OUT_TOP
  elsif y > self.y + self.height
      out |= OUT_BOTTOM
  end
  out
end