Created
July 15, 2009 23:53
-
-
Save tomlea/148065 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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