Skip to content

Commit

Permalink
[ReactNative] Added support for 3 digit hex colors | Arthur Lee
Browse files Browse the repository at this point in the history
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 facebook#455
Github Author: Arthur Lee <[email protected]>

Test Plan: Tried a couple of colors in the sample app, like `#FACEB0`, `#F00`, etc.
  • Loading branch information
arthuralee committed Apr 1, 2015
1 parent 92a6c3e commit 2d42c9e
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion React/Base/RCTConvert.m
Original file line number Diff line number Diff line change
Expand Up @@ -459,7 +459,17 @@ + (UIColor *)UIColor:(id)json
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);
Expand Down

0 comments on commit 2d42c9e

Please sign in to comment.