Skip to content

Instantly share code, notes, and snippets.

@lynnlx lynnlx/colorFromHex.m
Last active Aug 13, 2019

Embed
What would you like to do?
[Objective-C] RGBA Color from hex color [string]
/**
* RGBA Color from hex color
*
* @param hex Hex color
* @return NSColor object(nil if failure)
*/
- (nullable NSColor *)colorFromHex:(NSUInteger)hex {
unsigned char r, g, b;
if (hex & ~0xffffffUL) return nil;
r = (unsigned char) (hex >> 16);
g = (unsigned char) (hex >> 8);
b = (unsigned char) hex;
return [NSColor colorWithRed:(CGFloat) r / 0xff
green:(CGFloat) g / 0xff
blue:(CGFloat) b / 0xff
alpha:1.0];
}
/**
* RGBA Color from hex color string
*
* @param hexString Hex color string
* Optionally prefixed with "0x" or "0X" or "#"
* @return NSColor object(nil if failure)
*
* see:
* https://www.uicolor.xyz/#/hex-to-ui
* https://stackoverflow.com/questions/8697205/convert-hex-color-code-to-nscolor
*/
- (nullable NSColor *)colorFromHexString:(nonnull NSString *)hexString {
unsigned int hex = 0;
if (hexString == nil) return nil;
if ([hexString hasPrefix:@"#"]) {
hexString = [hexString substringFromIndex:1];
}
if ([[NSScanner scannerWithString:hexString] scanHexInt:&hex]) {
return [self colorFromHex:hex];
}
return nil;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.