首页 > 代码库 > iOS 获取UIColor对象的rgb值。

iOS 获取UIColor对象的rgb值。




/**

 *  获取UIColor对象的rgb值。

 *

 *  @param originColor

 *

 *  @return

 */

- (NSString *)getHexStringByColor:(UIColor *)originColor

{

 NSDictionary *colorDic= [self getRGBDictionaryByColor:originColor];

 int r = [colorDic[@"R"]floatValue] * 255;

 int g = [colorDic[@"G"]floatValue] * 255;

 int b = [colorDic[@"B"]floatValue] * 255;

 NSString *red = [NSStringstringWithFormat:@"%02x", r];

 NSString *green = [NSStringstringWithFormat:@"%02x", g];

 NSString *blue = [NSStringstringWithFormat:@"%02x", b];

  

 return [NSStringstringWithFormat:@"#%@%@%@", red, green, blue];

}


- (NSDictionary *)getRGBDictionaryByColor:(UIColor *)originColor

{

 CGFloat r=0,g=0,b=0,a=0;

 if ([self respondsToSelector:@selector(getRed:green:blue:alpha:)]) {

    [originColorgetRed:&r green:&gblue:&b alpha:&a];

  }

 else {

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

    r = components[0];

    g = components[1];

    b = components[2];

    a = components[3];

  }

  

 return @{@"R":@(r),

          @"G":@(g),

          @"B":@(b),

          @"A":@(a)};

}


iOS 获取UIColor对象的rgb值。