Module: Vector2d::Fitting
- Included in:
- Vector2d
- Defined in:
- lib/vector2d/fitting.rb
Instance Method Summary collapse
-
#contain(other) ⇒ Object
Scales down the given vector unless it fits inside.
-
#fit(other) ⇒ Object
(also: #constrain_both)
Scales the vector to fit inside another vector, retaining the aspect ratio.
-
#fit_either(other) ⇒ Object
(also: #constrain_one)
Constrain/expand so that one of the coordinates fit within (the square implied by) another vector.
Instance Method Details
#contain(other) ⇒ Object
12 13 14 15 |
# File 'lib/vector2d/fitting.rb', line 12 def contain(other) v, = coerce(other) v.x > x || v.y > y ? other.fit(self) : other end |
#fit(other) ⇒ Object Also known as: constrain_both
Scales the vector to fit inside another vector, retaining the aspect ratio.
vector = Vector2d(20, 10)
vector.fit(Vector2d(10, 10)) # => Vector2d(10,5)
vector.fit(Vector2d(20, 20)) # => Vector2d(20,10)
vector.fit(Vector2d(40, 40)) # => Vector2d(40,20)
Note: Either axis will be disregarded if zero or nil. This is a feature, not a bug.
28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/vector2d/fitting.rb', line 28 def fit(other) v, = coerce(other) scale = v.to_f_vector / self self * ( if scale.y.zero? || (scale.x.positive? && scale.x < scale.y) scale.x else scale.y end ) end |
#fit_either(other) ⇒ Object Also known as: constrain_one
48 49 50 51 52 53 54 55 56 57 |
# File 'lib/vector2d/fitting.rb', line 48 def fit_either(other) v, = coerce(other) scale = v.to_f_vector / self if scale.x.positive? && scale.y.positive? scale = [scale.x, scale.y].max self * scale else fit(v) end end |