Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

macos - How to convert hex to NSColor?

I have this function which transform a color in hexString :

public extension NSColor {
    func getHexString() -> String {
        let red = Int(round(self.redComponent * 0xFF))
        let green = Int(round(self.greenComponent * 0xFF))
        let blue = Int(round(self.blueComponent * 0xFF))
        let hexValue = NSString(format: "#%02X%02X%02X", red, green, blue)
        return hexValue
    }
}

Now , i have no idea how to reverse this. All i have is this objective-c code , but i'm not able to convert it to swift.

 (NSColor*)colorWithHexColorString:(NSString*)inColorString
{
    NSColor* result = nil;
    unsigned colorCode = 0;
    unsigned char redByte, greenByte, blueByte;

    if (nil != inColorString)
    {
         NSScanner* scanner = [NSScanner scannerWithString:inColorString];
         (void) [scanner scanHexInt:&colorCode]; 
    }
    redByte = (unsigned char)(colorCode >> 16);
    greenByte = (unsigned char)(colorCode >> 8);
    blueByte = (unsigned char)(colorCode);

    result = [NSColor
    colorWithCalibratedRed:(CGFloat)redByte
    green:(CGFloat)greenByte 
    blue:(CGFloat)blueByte 
    alpha:1.0];
    return result;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I can't believe I'm doing this, but with all due respect, I was disturbed by the way "insane-36" was resorting to NSScanner and NSString - it all just seemed too heavyweight - so here's my "pure" Swift version, which is not actually "pure" because I ended up calling strtol:

func hexStringToColor(var s:String) -> UIColor {
    if s.hasPrefix("#") { s = dropFirst(s) }
    var arr = [String]()
    for i in stride(from: 0, through: 4, by: 2) {
        let ix = advance(s.startIndex,i)
        let ix2 = advance(s.startIndex,i+1)
        arr.append(s[ix...ix2])
    }
    let rgb = arr.map{CGFloat(strtol($0,nil,16))/255.0}
    return UIColor(red: rgb[0], green: rgb[1], blue: rgb[2], alpha: 1)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...