fix: crash on systemPreferences.getAccentColor() (#18144)

This commit is contained in:
Shelley Vohr 2019-05-07 08:26:34 -07:00 committed by GitHub
parent d79dc056bc
commit 0ab3d7a0be
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 58 additions and 22 deletions

View file

@ -10,6 +10,8 @@
#import <Cocoa/Cocoa.h>
@interface NSColor (Hex)
- (NSString*)hexadecimalValue;
- (NSString*)RGBAValue;
+ (NSColor*)colorWithHexColorString:(NSString*)hex;
@end

View file

@ -8,17 +8,65 @@
@implementation NSColor (Hex)
- (NSString*)RGBAValue {
double redFloatValue, greenFloatValue, blueFloatValue, alphaFloatValue;
NSColor* convertedColor =
[self colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
if (convertedColor) {
[convertedColor getRed:&redFloatValue
green:&greenFloatValue
blue:&blueFloatValue
alpha:&alphaFloatValue];
int redIntValue = redFloatValue * 255.99999f;
int greenIntValue = greenFloatValue * 255.99999f;
int blueIntValue = blueFloatValue * 255.99999f;
int alphaIntValue = alphaFloatValue * 255.99999f;
return
[NSString stringWithFormat:@"%02x%02x%02x%02x", redIntValue,
greenIntValue, blueIntValue, alphaIntValue];
}
return nil;
}
- (NSString*)hexadecimalValue {
double redFloatValue, greenFloatValue, blueFloatValue;
NSColor* convertedColor =
[self colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
if (convertedColor) {
[convertedColor getRed:&redFloatValue
green:&greenFloatValue
blue:&blueFloatValue
alpha:NULL];
int redIntValue = redFloatValue * 255.99999f;
int greenIntValue = greenFloatValue * 255.99999f;
int blueIntValue = blueFloatValue * 255.99999f;
return [NSString stringWithFormat:@"#%02x%02x%02x", redIntValue,
greenIntValue, blueIntValue];
}
return nil;
}
+ (NSColor*)colorWithHexColorString:(NSString*)inColorString {
unsigned colorCode = 0;
unsigned char redByte, greenByte, blueByte;
if (inColorString) {
NSScanner* scanner = [NSScanner scannerWithString:inColorString];
(void)[scanner scanHexInt:&colorCode]; // ignore error
}
redByte = (unsigned char)(colorCode >> 16);
greenByte = (unsigned char)(colorCode >> 8);
blueByte = (unsigned char)(colorCode); // masks off high bits
unsigned char redByte = (unsigned char)(colorCode >> 16);
unsigned char greenByte = (unsigned char)(colorCode >> 8);
unsigned char blueByte = (unsigned char)(colorCode); // masks off high bits
return [NSColor colorWithCalibratedRed:(CGFloat)redByte / 0xff
green:(CGFloat)greenByte / 0xff