From 2d42c9eb4aa0e734387438b902402071823af0ad Mon Sep 17 00:00:00 2001 From: Arthur Lee Date: Tue, 31 Mar 2015 20:24:23 -0700 Subject: [PATCH] [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 Test Plan: Tried a couple of colors in the sample app, like `#FACEB0`, `#F00`, etc. --- React/Base/RCTConvert.m | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/React/Base/RCTConvert.m b/React/Base/RCTConvert.m index 9aea12727..10a8fbd54 100644 --- a/React/Base/RCTConvert.m +++ b/React/Base/RCTConvert.m @@ -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);