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

时间:2014-10-13 13:21:25

标签: ios objective-c iphone ipad uicolor

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

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

我有这段代码:

- (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)];

}

我检查过的链接:

hex color from uicolor

How to convert HEX RGB color codes to UIColor?

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

感谢任何回答的人。

我在viewDidLoad中使用什么代码调用此方法才能在NSLog中显示?

13 个答案:

答案 0 :(得分:50)

使用以下代码:

- (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)];
}

获取十六进制代码字符串后,请调用以下方法获取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;
}

USAGE

// ( 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];

答案 1 :(得分:21)

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

答案 2 :(得分:17)

最后使用 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)
            )
        }
    }
}

答案 3 :(得分:8)

对于像白色这样的UIColors,

其他Swift回答崩溃,其中CGColor只返回了2个组件。

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

例如:

白色将返回 #FFFFFF

白色,不透明度为50%会返回#FFFFFF7F

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

答案 4 :(得分:6)

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

答案 5 :(得分:3)

Swift 2版本接受的答案。我转换为func countUp(start: Int, end: Int, delay: Double) { if start <= end { let del = delay * Double(NSEC_PER_SEC) let time = dispatch_time(DISPATCH_TIME_NOW, Int64(del)) dispatch_after(time, dispatch_get_main_queue()) { print("\(start)") // Your rendering code here countUp(start + 1, end: end, delay: delay) } } else { let del = delay * Double(NSEC_PER_SEC) let time = dispatch_time(DISPATCH_TIME_NOW, Int64(del)) dispatch_after(time, dispatch_get_main_queue()) { print("I'm done!") // Your continuation code here // Please not that you should, for clarity and maintenance, wrap your delayed execution code inside a function..... } } } countUp(10, end: 20, delay: 1) 扩展名。

UIColor

答案 6 :(得分:1)

swift 2的答案转换为swift 3

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

答案 7 :(得分:1)

处理Alpha时的潜在陷阱:HEX字符串有不同的格式,有些字符串在十六进制字符串的开头有alpha,其他格式在结尾处有。根据您的背景,您可能对十六进制字符串的格式有不同的看法。对于Android开发人员来说,它可能会在开始时使用alpha,对于Web开发人员来说,它可能会在字符串的末尾。 总是声明HEX STRING的格式以避免混淆。 Android十六进制字符串需要在开始时具有alpha。因此,当涉及到十六进制字符串时,人们可能陷入陷阱(我这样做),因此重要的是要说明预期的格式是什么。因此,如果您正在为iOS和Android开发适用于此陷阱的应用程序。

链接: 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

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

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

+(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)
            ];

}

答案 8 :(得分:1)

如果您需要Android的颜色,这是正确的顺序。 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(alpha * multiplier),
                Int(red * multiplier),
                Int(green * multiplier),
                Int(blue * multiplier)
            )
        }
    }
}

然后致电:

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

答案 9 :(得分:1)

快捷方式:

extension UIColor {
    var hexString: String {
        return cgColor.components![0..<3]
            .map { String(format: "%02lX", Int($0 * 255)) }
            .reduce("#", +)
    }
}

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

答案 10 :(得分:1)

根据 Kampai 的回答,这是 SwiftUI 版本。

extension Color {
    func hexString() -> String {
        let components = self.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)))
        return hexString
    }
}

答案 11 :(得分:0)

快捷键5

extension Collection {
    public subscript(safe index: Index) -> Element? {
        return startIndex <= index && index < endIndex ? self[index] : nil
    }
}
extension UIColor {
    var hexString: String {
        let components = cgColor.components
        let r: CGFloat = components?[safe: 0] ?? 0.0
        let g: CGFloat = components?[safe: 1] ?? 0.0
        let b: CGFloat = components?[safe: 2] ?? 0.0

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

        return hexString
    }
}

答案 12 :(得分:0)

我正在使用此扩展程序:(Swift 5.x)如果您将颜色作为 .white 传递,则会得到 #ffffff

import UIKit
extension UIColor {
    convenience init(hexString: String, alpha: CGFloat = 1.0) {
        let hexString: String = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        let scanner = Scanner(string: hexString)
        if (hexString.hasPrefix("#")) {
            scanner.scanLocation = 1
        }
        var color: UInt32 = 0
        scanner.scanHexInt32(&color)
        let mask = 0x000000FF
        let r = Int(color >> 16) & mask
        let g = Int(color >> 8) & mask
        let b = Int(color) & mask
        let red   = CGFloat(r) / 255.0
        let green = CGFloat(g) / 255.0
        let blue  = CGFloat(b) / 255.0
        self.init(red:red, green:green, blue:blue, alpha:alpha)
    }

    func hexStringFromColor() -> String {
        var r:CGFloat = 0
        var g:CGFloat = 0
        var b:CGFloat = 0
        var a:CGFloat = 0
        getRed(&r, green: &g, blue: &b, alpha: &a)
        let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
        return String(format:"#%06x", rgb)
    }
}

用法:

let color = UIColor(hexString: "#3f3f3f")
or
color.hexStringFromColor()