[ReactNative] Added support for 3 digit hex colors | Arthur Lee

Summary:
This addition adds a check for whether a hex color is 3 or 6 digits. If it is 3 digits, it will expand the short form into 6 digits, just like in CSS. The additional benefit of having the length check is that hex colors of invalid lengths (like 4 digits) will be considered invalid. In CSS, invalid length hex colors returns white, but here I have logged an error through `RCTLogError`.
Closes https://github.com/facebook/react-native/pull/455
Github Author: Arthur Lee <arthur@arthurlee.me>

Test Plan: Tried a couple of colors in the sample app, like `#FACEB0`, `#F00`, etc.
This commit is contained in:
Arthur Lee 2015-03-31 20:24:23 -07:00
parent 92a6c3e004
commit 2d42c9eb4a
1 changed files with 11 additions and 1 deletions

View File

@ -459,7 +459,17 @@ RCT_CGSTRUCT_CONVERTER(CGAffineTransform, (@[
NSUInteger blue = -1;
CGFloat alpha = 1.0;
if ([colorString hasPrefix:@"#"]) {
sscanf([colorString UTF8String], "#%02tX%02tX%02tX", &red, &green, &blue);
if (colorString.length == 4) { // 3 digit hex
sscanf([colorString UTF8String], "#%01tX%01tX%01tX", &red, &green, &blue);
// expand to 6 digit hex
red = red | (red << 4);
green = green | (green << 4);
blue = blue | (blue << 4);
} else if (colorString.length == 7) { // normal 6 digit hex
sscanf([colorString UTF8String], "#%02tX%02tX%02tX", &red, &green, &blue);
} else {
RCTLogError(@"Invalid hex color %@. Hex colors should be 3 or 6 digits long", colorString);
}
} else if ([colorString hasPrefix:@"rgba("]) {
double tmpAlpha;
sscanf([colorString UTF8String], "rgba(%zd,%zd,%zd,%lf)", &red, &green, &blue, &tmpAlpha);