How do I convert a UIColor to a hexadecimal string?

后端 未结 3 602
独厮守ぢ
独厮守ぢ 2021-02-04 08:28

I have a project where I need to store the RGBA values of a UIColor in a database as an 8-character hexadecimal string. For example, [UIColor blueColor] would be @\"0000FFFF\".

3条回答
  •  梦毁少年i
    2021-02-04 08:43

    Here it goes. Returns a NSString (e.g. ffa5678) with a hexadecimal value of the color.

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

提交回复
热议问题