如何将 UIColor 转换为十六进制(网页颜色文本字符串)?

发布于 2024-12-24 15:45:49 字数 166 浏览 0 评论 0原文

有没有一种简单的方法可以将 UIColor 转换为十六进制值?
或者我们是否必须使用 CGColorGetComponents 获取 RGB 分量,然后从那里计算出来?

例如 CGColorGetComponents(color.CGColor)[0] * 256 ?

Is there an easy way to convert UIColor to a hexadecimal value ?
Or do we have to get the RGB components with CGColorGetComponents and then work it out from there?

e.g CGColorGetComponents(color.CGColor)[0] * 256 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

葬﹪忆之殇 2024-12-31 15:45:49

我还必须将 UIColor 转换为其十六进制组件。

正如 lewiguez 已经指出的那样,github 上有一个非常好的类别可以完成所有这些工作。

但因为我想了解它是如何完成的,所以我自己制作了 RGB 颜色的简单实现。

+ (NSString*)colorToWeb:(UIColor*)color
{
    NSString *webColor = nil;

    // This method only works for RGB colors
    if (color &&
        CGColorGetNumberOfComponents(color.CGColor) == 4)
    {
        // Get the red, green and blue components
        const CGFloat *components = CGColorGetComponents(color.CGColor);

        // These components range from 0.0 till 1.0 and need to be converted to 0 till 255
        CGFloat red, green, blue;
        red = roundf(components[0] * 255.0);
        green = roundf(components[1] * 255.0);
        blue = roundf(components[2] * 255.0);

        // Convert with %02x (use 02 to always get two chars)
        webColor = [[NSString alloc]initWithFormat:@"%02x%02x%02x", (int)red, (int)green, (int)blue];
    }

    return webColor;
}

欢迎所有反馈!

I also had to convert a UIColor to its hex components.

As already pointed out by lewiguez there is a very good category at github that does all that stuff.

But because I wanted to learn how it is done I made my own simple implementation for RGB colours.

+ (NSString*)colorToWeb:(UIColor*)color
{
    NSString *webColor = nil;

    // This method only works for RGB colors
    if (color &&
        CGColorGetNumberOfComponents(color.CGColor) == 4)
    {
        // Get the red, green and blue components
        const CGFloat *components = CGColorGetComponents(color.CGColor);

        // These components range from 0.0 till 1.0 and need to be converted to 0 till 255
        CGFloat red, green, blue;
        red = roundf(components[0] * 255.0);
        green = roundf(components[1] * 255.0);
        blue = roundf(components[2] * 255.0);

        // Convert with %02x (use 02 to always get two chars)
        webColor = [[NSString alloc]initWithFormat:@"%02x%02x%02x", (int)red, (int)green, (int)blue];
    }

    return webColor;
}

All feedback is welcome!

握住你手 2024-12-31 15:45:49

我会考虑使用 Erica Sadun 的 UIColor 类别。它包含许多免费功能,包括十六进制表示。它非常容易使用,只需将其添加到您使用它的任何类标头中,或者将其添加到预编译标头中以获得最终的灵活性。
如果您要添加到预编译标头,请执行类似于以下操作:

#ifdef __OBJC__
    #import <Foundation/Foundation.h>
    #import <UIKit/UIKit.h>
    #import "UIColor-Expanded.h"
#endif

然后您可以像这样使用它 NSLog(@"%@", [myColor hexStringFromColor]);

GitHub 链接到 UIColor 类别:https://github.com/erica/uicolor-utilities

ArsTechnica 文章有关它: http://arstechnica.com/apple/guides /2009/02/iphone-development-accessing-uicolor-components.ars

I would consider using Erica Sadun's UIColor category. It includes a lot of functionality for free, including hex representations. It's pretty easy to use, just add it to whatever class header you're using it in or, add it to the pre-compiled header for ultimate flexibility.
If you're adding to the pre-compiled header, do so similar to something like this:

#ifdef __OBJC__
    #import <Foundation/Foundation.h>
    #import <UIKit/UIKit.h>
    #import "UIColor-Expanded.h"
#endif

Then You can use it like so NSLog(@"%@", [myColor hexStringFromColor]);

GitHub link to the UIColor category: https://github.com/erica/uicolor-utilities

ArsTechnica article about it: http://arstechnica.com/apple/guides/2009/02/iphone-development-accessing-uicolor-components.ars

风柔一江水 2024-12-31 15:45:49

除了广泛使用的基于字符串的解决方案之外,这里还有一个基于十六进制(整数)的解决方案。用法:

UIColor* color = lf_rgb(0x120aef);
log(@"color %.6x", color.hex_rgb);

你会得到“color 120aef”。我会将这些代码放在 https://github.com/superarts/LCategory 中,或者您可以复制-也粘贴到您自己的代码库中:

#define lf_rgb(rgbValue)    [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

@interface UIColor (lc_rgb)
- (NSInteger)hex_rgb;
@end

@implementation UIColor (lc_rgb)
- (NSInteger)hex_rgb
{
    CGFloat r, g, b, a;
    BOOL result = [self getRed:&r green:&g blue:&b alpha:&a];
    //  log(@"rgba: %f, %f, %f, %f", r * 255, g * 255, b * 255, a * 255);
    if ((result == NO) || (a != 1.0f))
        return -1;
    return 
        (NSInteger)(r * 255) * 256 * 256 + 
        (NSInteger)(g * 255) * 256 +
        (NSInteger)(b * 255) * 1;
}
@end

Other than the widely used string based solution, here's a hex (integer) based solution. Usage:

UIColor* color = lf_rgb(0x120aef);
log(@"color %.6x", color.hex_rgb);

And you'll get "color 120aef". I'll put these code in https://github.com/superarts/LCategory, or you can copy-paste into your own code bank too:

#define lf_rgb(rgbValue)    [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

@interface UIColor (lc_rgb)
- (NSInteger)hex_rgb;
@end

@implementation UIColor (lc_rgb)
- (NSInteger)hex_rgb
{
    CGFloat r, g, b, a;
    BOOL result = [self getRed:&r green:&g blue:&b alpha:&a];
    //  log(@"rgba: %f, %f, %f, %f", r * 255, g * 255, b * 255, a * 255);
    if ((result == NO) || (a != 1.0f))
        return -1;
    return 
        (NSInteger)(r * 255) * 256 * 256 + 
        (NSInteger)(g * 255) * 256 +
        (NSInteger)(b * 255) * 1;
}
@end
悲念泪 2024-12-31 15:45:49

据我所知,没有任何内置的解决方案。
但请注意,您应该乘以 255 而不是 256

获取十六进制表示是一项简单的任务,因此手动构建字符串不会遇到很多麻烦。

NSLog(@"%X%X%X", redInteger, greenInteger, blueInteger);

There isn't, as far as I know, any built in solution.
Note however, that you should multiply by 255 instead of 256.

Getting an hexadecimal representation is an easy task, so you won't have many troubles to build the string manually.

NSLog(@"%X%X%X", redInteger, greenInteger, blueInteger);
幸福不弃 2024-12-31 15:45:49

这就是我使用 Swift 3 所做的:

extension UIColor {
    var hex:String{
        get{
            var red:CGFloat = 0
            var blue:CGFloat = 0
            var green:CGFloat = 0
            var alpha:CGFloat = 0

            self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
            let rgb:Int = (Int)(red*255)<<16 | (Int)(green*255)<<8 | (Int)(blue*255)<<0
            return String.localizedStringWithFormat("#%06x", rgb)
        }
    }
}

或者你可以将其设为一个方法。我只是喜欢 color.hexcolor.hex() 的外观。

This is how I do did it with Swift 3:

extension UIColor {
    var hex:String{
        get{
            var red:CGFloat = 0
            var blue:CGFloat = 0
            var green:CGFloat = 0
            var alpha:CGFloat = 0

            self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
            let rgb:Int = (Int)(red*255)<<16 | (Int)(green*255)<<8 | (Int)(blue*255)<<0
            return String.localizedStringWithFormat("#%06x", rgb)
        }
    }
}

Or you can make it a method. I just like how color.hex looks vs color.hex().

优雅的叶子 2024-12-31 15:45:49

这是一个 Swift 5 解决方案,作为 UIColor 的扩展,将 UIColor 对象转换为 RGB (#RRGGBB) 形式或 RGBA (#RRGGBBAA) 格式的十六进制颜色字符串,也可以使用任一格式并创建 UIColor,并可选择提供带有 #RRGGBB 形式的 alpha 参数作为 alpha 的非默认值 1.0。

我从 @boidkan 的答案开始,然后在 SO 上搜索其他解决方案,然后将它们细化和优化为我可以接受的解决方案,并在操场上测试它们。

/* Returns UIColor as "#RRGGBB" (hex string) */
var hexRGB : String {
    func comp(_ value: CGFloat, _ byteShift: Int = 0) -> Int { return Int(value * 0xff) << (byteShift * 8) }
    var r = CGFloat(0), b = CGFloat(0), g = CGFloat(0), a = CGFloat(0)
    getRed(&r, green: &g, blue: &b, alpha: &a)
    return String(format: "#%6.6X", comp(r, 2) | comp(g, 1) | comp(b))
}

/* Returns UIColor as "#RRGGBBAA" (hex string) */
var hexRGBA : String {
    func comp(_ value: CGFloat, _ byteShift: Int = 0) -> Int { return Int(value * 0xff) << (byteShift * 8) }
    var r = CGFloat(0), b = CGFloat(0), g = CGFloat(0), a = CGFloat(0)
    getRed(&r, green: &g, blue: &b, alpha: &a)
    return String(format: "#%8.8X", comp(r, 3) | comp(g, 2) | comp(b, 1) | comp(a))
}

/*
 * Returns UIColor object given input of the one of the following formats, where:
 *
 *       RR = Red component as hex value    00-FF
 *       GG = Green component as hex value  00-FF
 *       BB = Blue component as hex value   00-FF
 *       AA = Alpha componenet as hex value 00-FF
 *        a = Alpha component as 0.00 - 1.00 (a is optional, defaults to 1.0)
 *
 *       ("RRGGBB"[, a]),   ("#RRGGBB"[, a]), ("RRGGBBAA"), or ("#RRGGBBA")
 */
convenience init(hexRGBA: String, alpha: CGFloat = 1.0) {
    let cleanHex = hexRGBA.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
                          .replacingOccurrences(of: #"[^0-9a-fA-F]"#, with: "", options: .regularExpression)

    assert(cleanHex.count == 6 || cleanHex.count == 8, "Bad RGB/RGBA value")
    
    var rgbIntValue: UInt64 = 0
    Scanner(string:cleanHex).scanHexInt64(&rgbIntValue)
    let hh1 = CGFloat( Double((rgbIntValue & 0xff000000) >> 24)  / 255.0)
    let hh2 = CGFloat( Double((rgbIntValue & 0x00ff0000) >> 16)  / 255.0)
    let hh3 = CGFloat( Double((rgbIntValue & 0x0000ff00) >> 8)   / 255.0)
    let hh4 = CGFloat( Double((rgbIntValue & 0x000000ff)         / 255.0)
    if (cleanHex.count == 8) {
        self.init(red:  hh1, green: hh2, blue: hh3, alpha: hh4)
        return
    }
    self.init(red: hh2, green: hh3, blue: hh4, alpha: alpha) /* RGB + A */
}

Here's a Swift 5 solution, as extensions to UIColor, to convert UIColor object to a hex color string of RGB (#RRGGBB) form or RGBA (#RRGGBBAA) format ,and also use either format and create a UIColor, with option to provide an alpha argument with #RRGGBB form as non-default value of 1.0 for alpha.

I started with @boidkan's answer then searched around for other solutions on S.O. and then refined and optimized them to a solution I could live with, and tested them in playground.

/* Returns UIColor as "#RRGGBB" (hex string) */
var hexRGB : String {
    func comp(_ value: CGFloat, _ byteShift: Int = 0) -> Int { return Int(value * 0xff) << (byteShift * 8) }
    var r = CGFloat(0), b = CGFloat(0), g = CGFloat(0), a = CGFloat(0)
    getRed(&r, green: &g, blue: &b, alpha: &a)
    return String(format: "#%6.6X", comp(r, 2) | comp(g, 1) | comp(b))
}

/* Returns UIColor as "#RRGGBBAA" (hex string) */
var hexRGBA : String {
    func comp(_ value: CGFloat, _ byteShift: Int = 0) -> Int { return Int(value * 0xff) << (byteShift * 8) }
    var r = CGFloat(0), b = CGFloat(0), g = CGFloat(0), a = CGFloat(0)
    getRed(&r, green: &g, blue: &b, alpha: &a)
    return String(format: "#%8.8X", comp(r, 3) | comp(g, 2) | comp(b, 1) | comp(a))
}

/*
 * Returns UIColor object given input of the one of the following formats, where:
 *
 *       RR = Red component as hex value    00-FF
 *       GG = Green component as hex value  00-FF
 *       BB = Blue component as hex value   00-FF
 *       AA = Alpha componenet as hex value 00-FF
 *        a = Alpha component as 0.00 - 1.00 (a is optional, defaults to 1.0)
 *
 *       ("RRGGBB"[, a]),   ("#RRGGBB"[, a]), ("RRGGBBAA"), or ("#RRGGBBA")
 */
convenience init(hexRGBA: String, alpha: CGFloat = 1.0) {
    let cleanHex = hexRGBA.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
                          .replacingOccurrences(of: #"[^0-9a-fA-F]"#, with: "", options: .regularExpression)

    assert(cleanHex.count == 6 || cleanHex.count == 8, "Bad RGB/RGBA value")
    
    var rgbIntValue: UInt64 = 0
    Scanner(string:cleanHex).scanHexInt64(&rgbIntValue)
    let hh1 = CGFloat( Double((rgbIntValue & 0xff000000) >> 24)  / 255.0)
    let hh2 = CGFloat( Double((rgbIntValue & 0x00ff0000) >> 16)  / 255.0)
    let hh3 = CGFloat( Double((rgbIntValue & 0x0000ff00) >> 8)   / 255.0)
    let hh4 = CGFloat( Double((rgbIntValue & 0x000000ff)         / 255.0)
    if (cleanHex.count == 8) {
        self.init(red:  hh1, green: hh2, blue: hh3, alpha: hh4)
        return
    }
    self.init(red: hh2, green: hh3, blue: hh4, alpha: alpha) /* RGB + A */
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文