【问题标题】:How do I convert a UIColor to a hexadecimal string?如何将 UIColor 转换为十六进制字符串?
【发布时间】:2012-08-06 17:26:06
【问题描述】:

我有一个项目,我需要将 UIColor 的 RGBA 值作为 8 个字符的十六进制字符串存储在数据库中。例如,[UIColor blueColor] 将是 @"0000FFFF"。 我知道我可以像这样获得组件值:

CGFloat r,g,b,a;
[color getRed:&r green:&g blue: &b alpha: &a];

但我不知道如何从这些值转到十六进制字符串。我看过很多关于如何走另一条路的帖子,但对于这种转换没有任何作用。

【问题讨论】:

    标签: objective-c ios hex uicolor


    【解决方案1】:

    首先将您的浮点数转换为 int 值,然后使用 stringWithFormat 格式化:

        int r,g,b,a;
    
        r = (int)(255.0 * rFloat);
        g = (int)(255.0 * gFloat);
        b = (int)(255.0 * bFloat);
        a = (int)(255.0 * aFloat);
    
        [NSString stringWithFormat:@"%02x%02x%02x%02x", r, g, b, a];
    

    【讨论】:

    • 我之前尝试过类似的建议,但这个确实有效。
    • 方法 getRed:green:blue:alpha: 仅适用于 iOS 5+。 iOS 4 呢?
    • 可以在此处找到进行反向转换的好方法(例如,如果您从数据库/核心数据存储/加载颜色) - stackoverflow.com/a/12397366/553394
    • 请记住,调用 getRed:green:blue;alpha: 会因非 RGB 颜色(例如 [UIColor grayColor][UIColor whiteColor])而失败。所以这个解决方案只适用于某些颜色。
    【解决方案2】:

    来了。返回具有十六进制颜色值的 NSString(例如 ffa5678)。

    - (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 grayColor](或任何其他非RGB颜色)试试这个。结果不好或可能崩溃!
    【解决方案3】:

    Swift 4 通过扩展 UIColor 回答:

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

    【讨论】:

    • 我认为您的 Alpha 通道有错误。您错过了 * 255。它应该是 lroundf(Float(a * 255))
    猜你喜欢
    • 1970-01-01
    • 2013-02-07
    • 2011-03-01
    • 2017-08-23
    • 2014-03-19
    • 2011-08-25
    • 2014-04-28
    • 2018-01-31
    相关资源
    最近更新 更多