From 38cf14dd1872c39708eaa14cfa9b292314f2d1ef Mon Sep 17 00:00:00 2001 From: dwu185 Date: Sun, 28 Aug 2016 17:47:44 -0400 Subject: #1 Allow colors to be created with RGB hex values --- lib/ruby2d/color.rb | 17 ++++++++++++++--- 1 file changed, 14 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 -- cgit v1.2.3 From ad5543dc897eec7482b8076928f29aa00eedc9e4 Mon Sep 17 00:00:00 2001 From: dwu185 Date: Sun, 28 Aug 2016 18:00:57 -0400 Subject: unix tests edited --- spec/color_spec.rb | 6 ++++++ 1 file changed, 6 insertions(+) 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 -- cgit v1.2.3