2012-11-04 42 views
39

我想在我的项目中使用NSAttributedString,但是当我尝试设置不是标准设置的颜色(redColor,blackColor,greenColor等)时,UILabel会以白色显示这些字母。 这是我的这段代码。如何从RGBA创建UIColor?

[attributedString addAttribute:NSForegroundColorAttributeName 
         value:[UIColor colorWithRed:66 
               green:79 
               blue:91 
               alpha:1] 
         range:NSMakeRange(0, attributedString.length)]; 

我试图使色彩搭配CIColor从核心图像框架,但它显示了同样的结果。 我应该更改我的代码以正确的方式执行它?

Thx for answers,guys!

回答

95

您的值不正确,您需要将每个颜色值除以255.0。

[UIColor colorWithRed:66.0f/255.0f 
       green:79.0f/255.0f 
       blue:91.0f/255.0f 
       alpha:1.0f]; 

该文档状态:

+ (UIColor *)colorWithRed:(CGFloat)red 
        green:(CGFloat)green 
        blue:(CGFloat)blue 
        alpha:(CGFloat)alpha 

参数

红色 颜色对象的红色分量,指定为从0.0到1.0的值。

绿色 颜色对象的绿色分量,指定为从0.0到1.0的值。

蓝色 颜色对象的蓝色成分,指定为从0.0到1.0的值。

alpha 颜色对象的不透明度值,指定为从0.0到1.0的值。

Reference here.

+1

它工作得很好,现在我觉得自己像白痴这样的错误了!谢谢! – x401om

5

UIColor使用从0到1.0的范围内,而不是整数255 ..试试这个:

// create color 
UIColor *color = [UIColor colorWithRed:66/255.0 
           green:79/255.0 
            blue:91/255.0 
           alpha:1]; 

// use in attributed string 
[attributedString addAttribute:NSForegroundColorAttributeName 
         value:color 
         range:NSMakeRange(0, attributedString.length)]; 
+0

为什么是这样? –

3

请尝试像

Label.textColor=[UIColor colorWithRed:77.0/255.0f green:104.0/255.0f blue:159.0/255.0f alpha:1.0]; 
代码

[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:77.0/255.0f green:104.0/255.0f blue:159.0/255.0f alpha:1.0] range:NSMakeRange(0, attributedString.length)]; 

UIColor的RGB组件的缩放比例介于0和1之间,而不是255。

24

我最喜欢的宏,没有任何项目:

#define RGB(r, g, b) [UIColor colorWithRed:(float)r/255.0 green:(float)g/255.0 blue:(float)b/255.0 alpha:1.0] 
#define RGBA(r, g, b, a) [UIColor colorWithRed:(float)r/255.0 green:(float)g/255.0 blue:(float)b/255.0 alpha:a] 

使用,如:

[attributedString addAttribute:NSForegroundColorAttributeName 
         value:RGB(66, 79, 91) 
         range:NSMakeRange(0, attributedString.length)]; 
+0

为迅速吗? –

+1

嗨@JaswanthKumar检查我的'Swift'版本的答案。 –

2

由于@Jaswanth库马尔问,这里是从LSwiftSwift版本:

extension UIColor { convenience init(rgb:UInt, alpha:CGFloat = 1.0) { self.init( red: CGFloat((rgb & 0xFF0000) >> 16)/255.0, green: CGFloat((rgb & 0x00FF00) >> 8)/255.0, blue: CGFloat(rgb & 0x0000FF)/255.0, alpha: CGFloat(alpha) ) } }

用法:let color = UIColor(rgb: 0x112233)