iOS中UIColor转#开头的十六进制编码

2021-09-08  本文已影响0人  一代枭雄

话不多说,直接上代码

- (NSString *)hexadecimalFromUIColor: (UIColor*) color {

    if (CGColorGetNumberOfComponents(color.CGColor) < 4) {

       const CGFloat *components = CGColorGetComponents(color.CGColor);

       color = [UIColorcolorWithRed:components[0]

                           green:components[0]

                            blue:components[0]

                           alpha:components[1]];

    }

    if (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) != kCGColorSpaceModelRGB) {

       return [NSString stringWithFormat:@"#FFFFFF"];

    }

    NSString*r,*g,*b;

   (int)((CGColorGetComponents(color.CGColor))[0]*255.0) == 0?(r = [NSString stringWithFormat:@"0%x",(int)((CGColorGetComponents(color.CGColor))[0]*255.0)]):(r = [NSString stringWithFormat:@"%x",(int)((CGColorGetComponents(color.CGColor))[0]*255.0)]);

    (int)((CGColorGetComponents(color.CGColor))[1]*255.0) == 0?(g = [NSString stringWithFormat:@"0%x",(int)((CGColorGetComponents(color.CGColor))[1]*255.0)]):(g = [NSString stringWithFormat:@"%x",(int)((CGColorGetComponents(color.CGColor))[1]*255.0)]);

    (int)((CGColorGetComponents(color.CGColor))[2]*255.0) == 0?(b = [NSString stringWithFormat:@"0%x",(int)((CGColorGetComponents(color.CGColor))[2]*255.0)]):(b = [NSString stringWithFormat:@"%x",(int)((CGColorGetComponents(color.CGColor))[2]*255.0)]);

    self.ColorLab.text = [NSString stringWithFormat:@"#%@%@%@",r,g,b];

    return [NSString stringWithFormat:@"#%@%@%@",r,g,b];

}

上一篇下一篇

猜你喜欢

热点阅读