hex color from uicolor

前端 未结 4 1093
梦毁少年i
梦毁少年i 2021-01-04 08:56

i have a problem in converting uicolor to hex color, here what i found

CGColorRef colorref = [[Colorview_ backgroundColor] CGColor];

int numComponents = CG         


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-01-04 10:02

    Here is a version of this, but formatted as a C function:

    static inline NSString *hexFromUIColor(UIColor * _color) {
        if (CGColorGetNumberOfComponents(_color.CGColor) < 4) {
            const CGFloat *components = CGColorGetComponents(_color.CGColor);
            _color = [UIColor colorWithRed:components[0] green:components[0] blue:components[0] alpha:components[1]];
        }
        if (CGColorSpaceGetModel(CGColorGetColorSpace(_color.CGColor)) != kCGColorSpaceModelRGB) {
            return [NSString stringWithFormat:@"#FFFFFF"];
        }
        return [NSString stringWithFormat:@"#%02X%02X%02X", (int)((CGColorGetComponents(_color.CGColor))[0]*255.0), (int)((CGColorGetComponents(_color.CGColor))[1]*255.0), (int)((CGColorGetComponents(_color.CGColor))[2]*255.0)];
    }
    

提交回复
热议问题