Created
February 10, 2009 10:08
-
-
Save henrik/61335 to your computer and use it in GitHub Desktop.
Calculate opacity for hexadecimal colors in Ruby.
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
#!/usr/bin/env ruby | |
# | |
# Calculate opacity for hexadecimal colors. | |
# By Henrik Nyh <http://henrik.nyh.se> 2009-02-10 under the MIT License. | |
module Hexcolor | |
extend self | |
def opacity(fg, opa=1.0, bg='FFFFFF') | |
raise "Opacity must be between 0 and 1.0, but was #{opa}" unless (0..1.0).include?(opa) | |
fgs = fg.scan(/../) | |
bgs = bg.scan(/../) | |
fgs.zip(bgs).map do |fg,bg| | |
fg = fg.to_i(16) | |
bg = bg.to_i(16) | |
fg = (1 - opa) * bg + opa * fg | |
format('%02X', fg.round) | |
end.join | |
end | |
end | |
if __FILE__ == $0 | |
require 'test/unit' | |
class OpacityTest < Test::Unit::TestCase | |
def assert_opacity(expected_color, opa, input_color) | |
assert_equal(expected_color, Hexcolor.opacity(input_color, opa)) | |
end | |
def test_black | |
assert_opacity('FFFFFF', 0.0, '000000') | |
assert_opacity('808080', 0.5, '000000') | |
assert_opacity('000000', 1.0, '000000') | |
end | |
def test_white | |
assert_opacity('FFFFFF', 0.0, 'FFFFFF') | |
assert_opacity('FFFFFF', 0.5, 'FFFFFF') | |
assert_opacity('FFFFFF', 1.0, 'FFFFFF') | |
end | |
def test_red | |
assert_opacity('FFFFFF', 0.0, 'FF0000') | |
assert_opacity('FF8080', 0.5, 'FF0000') | |
assert_opacity('FF0000', 1.0, 'FF0000') | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment