本文介绍了如何将十六进制转换为 NSColor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个函数可以在 hexString 中转换颜色:

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
    }
}

现在,我不知道如何扭转这种情况.我所拥有的只是这个 Objective-c 代码,但我无法将其转换为 swift.

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;
    }

推荐答案

这里与 swift 完全相同,但是它使用 UIColor 而不是 NSColor,

Here is exact same thing with swift, however this uses UIColor rather than NSColor,

func colorWithHexColorString(var colorString: String) -> UIColor?
{
    if colorString.hasPrefix("#") {
        colorString = dropFirst(colorString)
    }

    var color: UIColor? = nil

    var colorCode = UInt32()

    var redByte:CGFloat = 255;
    var greenByte:CGFloat = 255;
    var blueByte: CGFloat = 255;

    let scanner = NSScanner(string: colorString)
    if scanner.scanHexInt(&colorCode) {
        redByte = CGFloat(colorCode & 0xff0000)
        greenByte = CGFloat(colorCode & 0x00ff00)
        blueByte =  CGFloat(colorCode & 0xff)
        color = UIColor(red: redByte, green: greenByte, blue: blueByte, alpha: 1.0)
    }

    return color
}

colorWithHexColorString("#ffff00")
colorWithHexColorString("ff0000")

这篇关于如何将十六进制转换为 NSColor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 17:40