summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorTom Black <[email protected]>2016-08-28 18:07:31 -0400
committerGitHub <[email protected]>2016-08-28 18:07:31 -0400
commit91676a0713c0dfd9a11c2b2b1ba0d50eb5d60534 (patch)
tree1293f008ccd3ca66c5f6d9e08883c3c450317b7e
parent03682597b91a4a2dfb8b2abbbc9551c68d3aa2dc (diff)
parentad5543dc897eec7482b8076928f29aa00eedc9e4 (diff)
downloadruby2d-91676a0713c0dfd9a11c2b2b1ba0d50eb5d60534.tar.gz
ruby2d-91676a0713c0dfd9a11c2b2b1ba0d50eb5d60534.zip
Merge pull request #17 from dwu185/RGBhexValue
#1 Allow colors to be created with RGB hex values
-rw-r--r--lib/ruby2d/color.rb17
-rw-r--r--spec/color_spec.rb6
2 files changed, 20 insertions, 3 deletions
diff --git a/lib/ruby2d/color.rb b/lib/ruby2d/color.rb
index 2768086..f39b3c1 100644
--- a/lib/ruby2d/color.rb
+++ b/lib/ruby2d/color.rb
@@ -35,6 +35,8 @@ module Ruby2D
when String
if c == 'random'
@r, @g, @b, @a = rand(0..1.0), rand(0..1.0), rand(0..1.0), 1.0
+ elsif self.class.is_hex(c)
+ @r, @g, @b, @a = hex_to_f(c)
else
@r, @g, @b, @a = to_f(@@colors[c])
end
@@ -43,10 +45,17 @@ module Ruby2D
end
end
end
-
+
+ # test whether input string is Hex color
+ def self.is_hex(a)
+ result = !(/^#[0-9A-F]{6}$/i.match(a).nil?)
+ return result
+ end
+
# Color must be String, like 'red', or Array, like [1.0, 0, 0, 1.0]
def self.is_valid?(c)
(c.class == String && @@colors.key?(c)) ||
+ (c.class == String && self.is_hex(c)) ||
(c.class == Array && c.length == 4 &&
c.all? { |el| el.is_a? Numeric } &&
c.all? { |el| el.class == Fixnum && (0..255).include?(el) ||
@@ -67,7 +76,8 @@ module Ruby2D
end
return b
end
- #convert from "#FFF000" to Float (0.0..1.0)
+
+ # convert from "#FFF000" to Float (0.0..1.0)
def hex_to_f(a)
c=[]
b=a.delete("#")
@@ -76,8 +86,9 @@ module Ruby2D
j=0
for i in (0..n-1).step(n/3)
c[j]=Integer("0x".concat(b[i,n/3]))
- j=j+1
+ j=j+1
end
+ c[3] = 255 #set @a to 255
f = to_f(c)
return f
end
diff --git a/spec/color_spec.rb b/spec/color_spec.rb
index deafe81..ed23712 100644
--- a/spec/color_spec.rb
+++ b/spec/color_spec.rb
@@ -7,6 +7,12 @@ RSpec.describe Ruby2D::Color do
expect(Ruby2D::Color.is_valid? 'red').to eq true
expect(Ruby2D::Color.is_valid? 'balloons').to eq false
end
+
+ it 'determines if a color string is valid hex value: # follow by 6 letters/numbers' do
+ expect(Ruby2D::Color.is_valid? '#c0c0c0').to eq true
+ expect(Ruby2D::Color.is_valid? '#00000').to eq false
+ expect(Ruby2D::Color.is_valid? '123456').to eq false
+ end
it 'determines if an array is a valid color' do
expect(Ruby2D::Color.is_valid? [1.0, 0, 0, 1.0]).to eq true