ios 如何将 UIColor 转换为 HEX 并在 NSLog 中显示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26341008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:09:51  来源:igfitidea点击:

How to convert UIColor to HEX and display in NSLog

iosobjective-cswiftiphoneuicolor

提问by App Dev Guy

I have checked several links on how to convert UIColor codes to HEX however I am not sure on how to call to the method to display them in NSLog. I haven't got the reputation to comment so posting as a question is my last resort. I want it to display when I run my app in the log.

我已经检查了几个关于如何将 UIColor 代码转换为 HEX 的链接,但是我不确定如何调用该方法以在 NSLog 中显示它们。我没有评论的声誉,所以作为问题发布是我最后的手段。我希望它在我在日志中运行我的应用程序时显示。

Second, where do I input the RGB color number ( R = 30, G = 171, B = 13)? I see that all examples use Array [0], [1], [2] which normally refers to index position, so where do I add the color values?

其次,我在哪里输入 RGB 颜色编号(R = 30,G = 171,B = 13)?我看到所有示例都使用 Array [0], [1], [2] 通常指的是索引位置,那么我在哪里添加颜色值?

I have this code:

我有这个代码:

- (NSString *) hexFromUIColor:(UIColor *)color {

    if (CGColorGetNumberOfComponents(color.CGColor) < 4) {
        const CGFloat *components = CGColorGetComponents(color.CGColor);
        color = [UIColor colorWithRed:components[30] green:components[141] blue:components[13] alpha:components[1]];
    }
    if (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) != kCGColorSpaceModelRGB) {
        return [NSString stringWithFormat:@"#FFFFFF"];
    }
    return [NSString stringWithFormat:@"#%02X%02X%02X", (int)((CGColorGetComponents(color.CGColor))[0]*255.0), (int)((CGColorGetComponents(color.CGColor))[1]*255.0), (int)((CGColorGetComponents(color.CGColor))[2]*255.0)];

}

Links I have checked:

我检查过的链接:

hex color from uicolor

来自 uicolor 的十六进制颜色

How to convert HEX RGB color codes to UIColor?

如何将 HEX RGB 颜色代码转换为 UIColor?

I have tried to call the method in viewDidLoad however it wont work without UIColor. I am sure it's something simple.

我曾尝试在 viewDidLoad 中调用该方法,但是如果没有 UIColor 它将无法工作。我相信这很简单。

Thanks to anyone who answers.

感谢任何回答的人。

What is the code I use in my viewDidLoad to call to this method in order to display in NSLog?

我在 viewDidLoad 中使用什么代码来调用此方法以便在 NSLog 中显示?

回答by Kampai

Swift 5:

斯威夫特 5:

func hexStringFromColor(color: UIColor) -> String {
    let components = color.cgColor.components
    let r: CGFloat = components?[0] ?? 0.0
    let g: CGFloat = components?[1] ?? 0.0
    let b: CGFloat = components?[2] ?? 0.0

    let hexString = String.init(format: "#%02lX%02lX%02lX", lroundf(Float(r * 255)), lroundf(Float(g * 255)), lroundf(Float(b * 255)))
    print(hexString)
    return hexString
 }

func colorWithHexString(hexString: String) -> UIColor {
    var colorString = hexString.trimmingCharacters(in: .whitespacesAndNewlines)
    colorString = colorString.replacingOccurrences(of: "#", with: "").uppercased()

    print(colorString)
    let alpha: CGFloat = 1.0
    let red: CGFloat = self.colorComponentFrom(colorString: colorString, start: 0, length: 2)
    let green: CGFloat = self.colorComponentFrom(colorString: colorString, start: 2, length: 2)
    let blue: CGFloat = self.colorComponentFrom(colorString: colorString, start: 4, length: 2)

    let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
    return color
}

func colorComponentFrom(colorString: String, start: Int, length: Int) -> CGFloat {

    let startIndex = colorString.index(colorString.startIndex, offsetBy: start)
    let endIndex = colorString.index(startIndex, offsetBy: length)
    let subString = colorString[startIndex..<endIndex]
    let fullHexString = length == 2 ? subString : "\(subString)\(subString)"
    var hexComponent: UInt32 = 0

    guard Scanner(string: String(fullHexString)).scanHexInt32(&hexComponent) else {
        return 0
    }
    let hexFloat: CGFloat = CGFloat(hexComponent)
    let floatValue: CGFloat = CGFloat(hexFloat / 255.0)
    print(floatValue)
    return floatValue
}

How to use

如何使用

let red =  CGFloat(30.0)
let green =  CGFloat(171.0)
let blue =  CGFloat(13.0)
let alpha =  CGFloat(1.0)

let color = UIColor(red: CGFloat(red/255.0), green: CGFloat(green/255.0), blue: CGFloat(blue / 255.0), alpha: alpha)
let colorCode = self.hexStringFromColor(color: color)
print(colorCode)

let resultColor = self.colorWithHexString(hexString: colorCode)
print(resultColor)

Objective-C:

目标-C:

- (NSString *)hexStringFromColor:(UIColor *)color {
    const CGFloat *components = CGColorGetComponents(color.CGColor);

    CGFloat r = components[0];
    CGFloat g = components[1];
    CGFloat b = components[2];

    return [NSString stringWithFormat:@"#%02lX%02lX%02lX",
            lroundf(r * 255),
            lroundf(g * 255),
            lroundf(b * 255)];
}

After getting hex code string, Call below method to get UIColor

得到十六进制码串后,调用下面的方法得到 UIColor

- (UIColor *) colorWithHexString: (NSString *) hexString
{
    NSString *colorString = [[hexString stringByReplacingOccurrencesOfString: @"#" withString: @""] uppercaseString];

    NSLog(@"colorString :%@",colorString);
    CGFloat alpha, red, blue, green;

    // #RGB
    alpha = 1.0f;
    red   = [self colorComponentFrom: colorString start: 0 length: 2];
    green = [self colorComponentFrom: colorString start: 2 length: 2];
    blue  = [self colorComponentFrom: colorString start: 4 length: 2];

    return [UIColor colorWithRed: red green: green blue: blue alpha: alpha];
}


- (CGFloat) colorComponentFrom: (NSString *) string start: (NSUInteger) start length: (NSUInteger) length {
    NSString *substring = [string substringWithRange: NSMakeRange(start, length)];
    NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat: @"%@%@", substring, substring];
    unsigned hexComponent;
    [[NSScanner scannerWithString: fullHex] scanHexInt: &hexComponent];
    return hexComponent / 255.0;
}

How to use

如何使用

// ( R = 30, G = 171, B = 13)? 
CGFloat red = 30.0;
CGFloat green = 171.0;
CGFloat blue = 13.0; 
CGFloat alpha = 255.0
UIColor *color = [UIColor colorWithRed:(red/255.0) green:(green/255.0) blue:(blue/255.0) alpha:(alpha/255.0)];
NSString *colorCode = [self hexStringFromColor:color];
NSLog(@"Color Code: %@", colorCode);

UIColor *resultColor = [self colorWithHexString:colorCode];

回答by Valentin Shergin

And finally the version which works with alpha-component and uses right multiplier

最后是与alpha 组件一起使用并使用正确乘数的版本

extension UIColor {
    var hexString: String? {
        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        var alpha: CGFloat = 0

        let multiplier = CGFloat(255.999999)

        guard self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) else {
            return nil
        }

        if alpha == 1.0 {
            return String(
                format: "#%02lX%02lX%02lX",
                Int(red * multiplier),
                Int(green * multiplier),
                Int(blue * multiplier)
            )
        }
        else {
            return String(
                format: "#%02lX%02lX%02lX%02lX",
                Int(red * multiplier),
                Int(green * multiplier),
                Int(blue * multiplier),
                Int(alpha * multiplier)
            )
        }
    }
}

回答by Jeff

Kampai's answer works for RGB colors, but not for monochrome (UIColor colorWithWhite:alpha:). It also doesn't handle alpha, which HEX supports. Here's a slightly modified version of hexStringFromColor:

Kampai 的答案适用于 RGB 颜色,但不适用于单色 (UIColor colorWithWhite:alpha:)。它也不处理 HEX 支持的 alpha。这是 hexStringFromColor 的一个稍微修改的版本:

+ (NSString *)hexStringFromColor:(UIColor *)color
{
    CGColorSpaceModel colorSpace = CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor));
    const CGFloat *components = CGColorGetComponents(color.CGColor);

    CGFloat r, g, b, a;

    if (colorSpace == kCGColorSpaceModelMonochrome) {
        r = components[0];
        g = components[0];
        b = components[0];
        a = components[1];
    }
    else if (colorSpace == kCGColorSpaceModelRGB) {
        r = components[0];
        g = components[1];
        b = components[2];
        a = components[3];
    }

    return [NSString stringWithFormat:@"#%02lX%02lX%02lX%02lX",
            lroundf(r * 255),
            lroundf(g * 255),
            lroundf(b * 255),
            lroundf(a * 255)];
}

回答by m_katsifarakis

Other Swift answers crash for UIColors like white, where there are only 2 components returned by CGColor.

UIColors 的其他 Swift 答案会崩溃,例如白色,其中 CGColor 仅返回 2 个组件。

Here's a Swift 4version that does not have that problem and also returns transparency information in the end of the string if that is required (web format).

这是一个没有这个问题的Swift 4版本,如果需要(网络格式),还会在字符串的末尾返回透明度信息。

The color is first converted to the sRGB colorspace before generating the HEX String to work properly even with Grayscale or other color spaces.

在生成 HEX 字符串之前,颜色首先转换为 sRGB 颜色空间,即使使用灰度或其他颜色空间也能正常工作。

For example:

例如:

White will return #FFFFFF

白色将返回#FFFFFF

White with 50% opacity will return #FFFFFF7F

不透明度为 50% 的白色将返回#FFFFFF7F

extension UIColor {
    var hexString: String {
        let cgColorInRGB = cgColor.converted(to: CGColorSpace(name: CGColorSpace.sRGB)!, intent: .defaultIntent, options: nil)!
        let colorRef = cgColorInRGB.components
        let r = colorRef?[0] ?? 0
        let g = colorRef?[1] ?? 0
        let b = ((colorRef?.count ?? 0) > 2 ? colorRef?[2] : g) ?? 0
        let a = cgColor.alpha

        var color = String(
            format: "#%02lX%02lX%02lX",
            lroundf(Float(r * 255)),
            lroundf(Float(g * 255)),
            lroundf(Float(b * 255))
        )

        if a < 1 {
            color += String(format: "%02lX", lroundf(Float(a * 255)))
        }

        return color
    }
}

OLD VERSION

旧版本

This version did not work properly with certain colors in non-RGB color spaces.

此版本无法在非 RGB 颜色空间中使用某些颜色正常工作。

extension UIColor {
    var hexString: String {
        let colorRef = cgColor.components
        let r = colorRef?[0] ?? 0
        let g = colorRef?[1] ?? 0
        let b = ((colorRef?.count ?? 0) > 2 ? colorRef?[2] : g) ?? 0
        let a = cgColor.alpha

        var color = String(
            format: "#%02lX%02lX%02lX",
            lroundf(Float(r * 255)),
            lroundf(Float(g * 255)),
            lroundf(Float(b * 255))
        )

        if a < 1 {
            color += String(format: "%02lX", lroundf(Float(a)))
        }

        return color
    }
}

回答by Joel Kopelioff

In Swift, I simply created an extension to UIColor...

在 Swift 中,我只是为 UIColor 创建了一个扩展......

extension UIColor
{

    var hexString:NSString {
        let colorRef = CGColorGetComponents(self.CGColor)

        let r:CGFloat = colorRef[0]
        let g:CGFloat = colorRef[1]
        let b:CGFloat = colorRef[2]

        return NSString(format: "#%02lX%02lX%02lX", lroundf(Float(r * 255)), lroundf(Float(g * 255)), lroundf(Float(b * 255)))
    }
}

回答by Isuru

Swift 2 version of the accepted answer. I converted into a UIColorextension.

已接受答案的 Swift 2 版本。我转换成UIColor扩展。

extension UIColor {
    var hexString: String {
        let components = CGColorGetComponents(self.CGColor)

        let red = Float(components[0])
        let green = Float(components[1])
        let blue = Float(components[2])
        return String(format: "#%02lX%02lX%02lX", lroundf(red * 255), lroundf(green * 255), lroundf(blue * 255))
    }
}

回答by MrG

This is the correct order if you need the colors for Android. the alpha goes first:

如果您需要 Android 的颜色,这是正确的顺序。阿尔法先行:

extension UIColor {
    var hexString: String? {
        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        var alpha: CGFloat = 0

        let multiplier = CGFloat(255.999999)

        guard self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) else {
            return nil
        }

        if alpha == 1.0 {
            return String(
                format: "#%02lX%02lX%02lX",
                Int(red * multiplier),
                Int(green * multiplier),
                Int(blue * multiplier)
            )
        }
        else {
            return String(
                format: "#%02lX%02lX%02lX%02lX",
                Int(alpha * multiplier),
                Int(red * multiplier),
                Int(green * multiplier),
                Int(blue * multiplier)
            )
        }
    }
}

Then call as:

然后调用为:

debugPrint("testColor > ", self.testColor().hexString!)

回答by Artem Sydorenko

Swift way:

快捷方式:

extension UIColor {
    var hexString: String {
        cgColor.components![0..<3]
            .map { String(format: "%02lX", Int(
    var hexString: String {
        var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0
        getRed(&r, green: &g, blue: &b, alpha: nil)
        return [r, g, b].map { String(format: "%02lX", Int(
var hexString: String {
    let components = self.cgColor.components

    let red = Float((components?[0])!)
    let green = Float((components?[1])!)
    let blue = Float((components?[2])!)
    return String(format: "#%02lX%02lX%02lX", lroundf(red * 255), lroundf(green * 255), lroundf(blue * 255))
}
* 255)) }.reduce("#", +) }
* 255)) } .reduce("#", +) } }

If you need hex with alpha just remove [0..<3]from code.

如果您需要带 alpha 的十六进制,只需[0..<3]从代码中删除。

Another safer implementation, that works fine with one component colors (like UIColor.white, UIColor.black):

另一个更安全的实现,它适用于一个组件颜色(如 UIColor.white、UIColor.black):

+(NSString*)hexStringFromColor:(UIColor *)color
{

    CGFloat r = 0, g = 0, b = 0, a = 1;

    if (color) {
        [color getRed:&r green:&g blue:&b alpha:&a];
    }

    return [NSString stringWithFormat:@"#%02lX%02lX%02lX%02lX",
            lroundf(a * 255.0),
            lroundf(r * 255.0),
            lroundf(g * 255.0),
            lroundf(b * 255.0)
            ];

}

回答by Haris

The swift 2 answer converted to swift 3

swift 2 的答案转换为 swift 3

##代码##

回答by Grant Luck

Potential Trap When Dealing With Alpha: HEX strings come in different formats, some have their alpha at the start of the hex string and other formats have it at the end. Depending on your background you may have a different idea of how the hex string is formatted. For Android developers it will likely be with the alpha at the start, for Web developers it will likely be at the end of the string. SO ALWAYS STATE THE FORMAT OF THE HEX STRINGto avoid confusion. Android hex strings are required to have the alpha at the start. So that is a trap people may fall into when it comes to hex strings (I did) and is thus important to say what the expected format is. So if you are developing an app for both iOS and Android what out for this trap.

处理 Alpha 时的潜在陷阱:十六进制字符串有不同的格式,有些在十六进制字符串的开头有它们的 alpha,而其他格式在末尾有它。根据您的背景,您可能对十六进制字符串的格式有不同的看法。对于 Android 开发人员,它可能会在开头带有 alpha,对于 Web 开发人员,它可能会在字符串的末尾。所以一定要说明十六进制字符串的格式以避免混淆。Android 十六进制字符串需要以字母开头。因此,这是人们在使用十六进制字符串时可能陷入的陷阱(我做到了),因此重要的是要说明预期的格式是什么。因此,如果您正在为 iOS 和 Android 开发应用程序,请注意这个陷阱。

Links: https://en.wikipedia.org/wiki/RGBA_color_spacefor details on why a HEX string maybe formatted in different ways, some cases with the alpha at the start. Android links https://developer.android.com/reference/android/graphics/Color.htmland https://gist.github.com/lopspower/03fb1cc0ac9f32ef38f4

链接:https: //en.wikipedia.org/wiki/RGBA_color_space详细了解为什么 HEX 字符串可能以不同方式格式化,某些情况下以 alpha 开头。Android 链接https://developer.android.com/reference/android/graphics/Color.htmlhttps://gist.github.com/lopspower/03fb1cc0ac9f32ef38f4

PLEASE NOTE FOR #AARRGGBBHex string format Use the following code so the Alpha is at the start of the string.

请注意 #AARRGGBB十六进制字符串格式 使用以下代码使 Alpha 位于字符串的开头。

(Note: if color == nullblack is returned).

(注意:如果color == null返回黑色)。

##代码##