UIColor to Hexadecimal (web color)

后端 未结 5 1410
悲&欢浪女
悲&欢浪女 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

    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
    

提交回复
热议问题