UIColor to Hexadecimal (web color)

后端 未结 5 1418
悲&欢浪女
悲&欢浪女 2021-02-15 23:37

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

5条回答
  •  忘了有多久
    2021-02-16 00:33

    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!

提交回复
热议问题