Skip to content

Instantly share code, notes, and snippets.

@tomlea
Created July 15, 2009 23:53
Show Gist options
  • Select an option

  • Save tomlea/148065 to your computer and use it in GitHub Desktop.

Select an option

Save tomlea/148065 to your computer and use it in GitHub Desktop.
class BaseColor
attr_reader :r,:g,:b,:a
def alpha(v)
BaseColor.new(r,g,b,v)
end
def initialize(r, g, b, a = 1.0)
@r, @g, @b, @a = normalize(r), normalize(g), normalize(b), normalize(a, 1.0)
end
def +(other)
case other
when Numeric
BaseColor.new(@r + other, @g + other, @b + other, @a)
else
BaseColor.new(@r + other.r, @g + other.g, @b + other.b, @a)
end
end
def -(other)
case other
when Numeric
BaseColor.new(@r - other, @g - other, @b - other, @a)
else
BaseColor.new(@r - other.r, @g - other.g, @b - other.b, @a)
end
end
def to_s
if a < 1.0
"rgba(#{r}, #{g}, #{b}, #{a})"
else
"#%02x%02x%02x" % [r,g,b]
end
end
def inspect
if a < 1.0
"rgba(#{r}, #{g}, #{b}, #{a})"
else
"rgb(#{r}, #{g}, #{b})"
end
end
def to_css
to_s
end
protected
def normalize(v, max = 255, min = 0)
[[min, v].max, max].min
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment