Module: Windraw::Color
- Defined in:
- lib/windraw/color.rb
Overview
Parses CSS-style hex colors into straight (non-premultiplied) RGBA floats in 0.0..1.0, the form Direct2D’s D2D1::ColorF expects.
Class Method Summary collapse
-
.parse(spec, default_alpha: 1.0) ⇒ Object
Accepts “#rgb”, “#rgba”, “#rrggbb”, “#rrggbbaa” (leading “#” optional).
Class Method Details
.parse(spec, default_alpha: 1.0) ⇒ Object
Accepts “#rgb”, “#rgba”, “#rrggbb”, “#rrggbbaa” (leading “#” optional). Returns [r, g, b, a] as floats in 0.0..1.0. Raises ArgumentError otherwise.
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/windraw/color.rb', line 11 def parse(spec, default_alpha: 1.0) unless spec.is_a?(String) || spec.respond_to?(:to_str) raise ArgumentError, "invalid hex color: #{spec.inspect} (expected a String)" end s = spec.to_s.strip s = s[1..] if s.start_with?("#") unless s.match?(/\A\h+\z/) raise ArgumentError, "invalid hex color: #{spec.inspect} (non-hex characters)" end case s.length when 3 # rgb r, g, b = s.chars.map { |c| (c * 2).to_i(16) } a = (default_alpha * 255).round when 4 # rgba r, g, b, a = s.chars.map { |c| (c * 2).to_i(16) } when 6 # rrggbb r, g, b = s.scan(/../).map { |h| h.to_i(16) } a = (default_alpha * 255).round when 8 # rrggbbaa r, g, b, a = s.scan(/../).map { |h| h.to_i(16) } else raise ArgumentError, "invalid hex color: #{spec.inspect} (use #rgb, #rgba, #rrggbb, or #rrggbbaa)" end [r / 255.0, g / 255.0, b / 255.0, a / 255.0] end |