在我的编辑器中,我有一个标签,在UITapGestureRecognizer上,我需要获取文本的颜色
NSLog(@"Fontcolor---- %@",sanlabel.textColor);但这段代码返回给我
UIDeviceRGBColorSpace 0.686275 1 1 1我如何获得正确格式的颜色代码,以便我可以将其用作
UIColorFromRGB(0X2c3836)发布于 2014-01-23 19:30:19
您可以使用此方法(取自here):
- (NSString *) htmlFromUIColor:(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)];
}发布于 2014-01-23 19:31:43
我假设你正在设置标签的文本,这是某种颜色定义,然后你想知道哪个标签被点击了?
我认为这是错误的方法,更好的方法是使用标签的标签来索引颜色定义的数组。这既更快,又允许您稍后更改标签的文本格式(可能是为了国际化),而不会影响功能。
因此,假设有3个标签;定义每个标签的颜色:
static unsigned _labelColours[3] = {
0x2c3836, 0x2c3837, 0x2c3838
};现在设置3个标签的标签从100开始(比方说)。这可以在代码中或在IB中完成。
然后,当您想知道分配给标签的颜色是什么时,只需在action方法中执行以下操作:
- (IBAction)labelWasTouched:(id)sender {
NSInteger tag = [sender tag];
NSAssert(tag >= 100 && tag <= 102, @"Tag out-of-range");
unsigned colour = _labelColours[tag - 100];
UIColor *colourObj = UIColorFromRGB(colour);
}发布于 2014-01-23 19:33:52
轻松地将UIDeviceRBGColorSpace中的每个值乘以255。然后使用NSString::stringWithFormat将值转换为带有%x的十六进制。
另外:
int r, g, b, a;
r = (int)(0.686275 * 255);
g = b = 1*255;
NSString *hexStr = [NSString stringWithFormat:@"%x%x%x",r,g,b];https://stackoverflow.com/questions/21306740
复制相似问题