class Prawn::SVG::Color

Constants

CMYK
CMYK_DEFAULT_COLOR
CMYK_REGEXP
HTML_COLORS
RGB
RGB_DEFAULT_COLOR
RGB_REGEXP
URL_REGEXP
VALUE_REGEXP

Public Class Methods

css_color_to_prawn_color(color) click to toggle source
# File lib/prawn/svg/color.rb, line 213
def self.css_color_to_prawn_color(color)
  result = parse(color).detect {|result| result.is_a?(RGB) || result.is_a?(CMYK)}
  result.value if result
end
parse(color_string, gradients = nil, color_mode = :rgb) click to toggle source
# File lib/prawn/svg/color.rb, line 163
def self.parse(color_string, gradients = nil, color_mode = :rgb)
  url_specified = false

  components = color_string.to_s.strip.scan(/([^(\s]+(\([^)]*\))?)/)

  result = components.map do |color, *_|
    if m = color.match(/\A#([0-9a-f])([0-9a-f])([0-9a-f])\z/i)
      RGB.new("#{m[1] * 2}#{m[2] * 2}#{m[3] * 2}")

    elsif color.match(/\A#[0-9a-f]{6}\z/i)
      RGB.new(color[1..6])

    elsif hex = HTML_COLORS[color.downcase]
      hex_color(hex, color_mode)

    elsif m = color.match(RGB_REGEXP)
      hex = (1..3).collect do |n|
        value = m[n].to_f
        value *= 2.55 if m[n][-1..-1] == '%'
        "%02x" % clamp(value.round, 0, 255)
      end.join

      RGB.new(hex)

    elsif m = color.match(CMYK_REGEXP)
      cmyk = (1..4).collect do |n|
        value = m[n].to_f
        value *= 100 unless m[n][-1..-1] == '%'
        clamp(value, 0, 100)
      end

      CMYK.new(cmyk)

    elsif matches = color.match(URL_REGEXP)
      url_specified = true
      url = matches[1]
      if url[0] == "#" && gradients && gradient = gradients[url[1..-1]]
        gradient
      end
    end
  end

  # Generally, we default to black if the colour was unparseable.
  # http://www.w3.org/TR/SVG/painting.html section 11.2 says if a URL was
  # supplied without a fallback, that's an error.
  result << default_color(color_mode) unless url_specified

  result.compact
end

Protected Class Methods

clamp(value, min_value, max_value) click to toggle source
# File lib/prawn/svg/color.rb, line 220
def self.clamp(value, min_value, max_value)
  [[value, min_value].max, max_value].min
end
default_color(color_mode) click to toggle source
# File lib/prawn/svg/color.rb, line 224
def self.default_color(color_mode)
  color_mode == :cmyk ? CMYK_DEFAULT_COLOR : RGB_DEFAULT_COLOR
end
hex_color(hex, color_mode) click to toggle source
# File lib/prawn/svg/color.rb, line 228
def self.hex_color(hex, color_mode)
  if color_mode == :cmyk
    r, g, b = [hex[0..1], hex[2..3], hex[4..5]].map { |h| h.to_i(16) / 255.0 }
    k = 1 - [r, g, b].max
    if k == 1
      CMYK.new([0, 0, 0, 100])
    else
      c = (1 - r - k) / (1 - k)
      m = (1 - g - k) / (1 - k)
      y = (1 - b - k) / (1 - k)
      CMYK.new([c, m, y, k].map { |v| (v * 100).round })
    end
  else
    RGB.new(hex)
  end
end