colors.hex: support varying length hex notations.

6 characters: rrggbb (1.0 alpha)
8 characters: rrggbbaa
3 characters: rgb (1.0 alpha)
4 characters: rgba
char-rename
John Benediktsson 2016-11-26 21:13:12 -08:00
parent 3b0d5bba15
commit 72cf4fec47
2 changed files with 18 additions and 3 deletions

View File

@ -7,3 +7,13 @@ USING: colors colors.hex tools.test ;
{ HEXCOLOR: abcdef } [ "abcdef" hex>rgba ] unit-test
{ HEXCOLOR: abcdef } [ "ABCDEF" hex>rgba ] unit-test
{ "ABCDEF" } [ HEXCOLOR: abcdef rgba>hex ] unit-test
{ HEXCOLOR: 00000000 } [ 0.0 0.0 0.0 0.0 <rgba> ] unit-test
{ HEXCOLOR: FF000000 } [ 1.0 0.0 0.0 0.0 <rgba> ] unit-test
{ HEXCOLOR: FFFF0000 } [ 1.0 1.0 0.0 0.0 <rgba> ] unit-test
{ HEXCOLOR: FFFFFF00 } [ 1.0 1.0 1.0 0.0 <rgba> ] unit-test
{ HEXCOLOR: FFFFFFFF } [ 1.0 1.0 1.0 1.0 <rgba> ] unit-test
{ HEXCOLOR: cafebabe } [ "cafebabe" hex>rgba ] unit-test
{ HEXCOLOR: 112233 } [ "123" hex>rgba ] unit-test
{ HEXCOLOR: 11223344 } [ "1234" hex>rgba ] unit-test

View File

@ -1,13 +1,18 @@
! Copyright (C) 2010 John Benediktsson
! See http://factorcode.org/license.txt for BSD license
USING: accessors colors formatting grouping kernel lexer math
math.parser sequences ;
USING: accessors colors combinators formatting grouping kernel
lexer math math.parser sequences ;
IN: colors.hex
: hex>rgba ( hex -- rgba )
2 group [ hex> 255 /f ] map first3 1.0 <rgba> ;
dup length {
{ 6 [ 2 group [ hex> 255 /f ] map first3 1.0 ] }
{ 8 [ 2 group [ hex> 255 /f ] map first4 ] }
{ 3 [ [ digit> 15 /f ] { } map-as first3 1.0 ] }
{ 4 [ [ digit> 15 /f ] { } map-as first4 ] }
} case <rgba> ;
: rgba>hex ( rgba -- hex )
[ red>> ] [ green>> ] [ blue>> ] tri