如何从RGBA创建UIColor?

49

我想在我的项目中使用NSAttributedString,但当我尝试设置非标准颜色(如redColorblackColorgreenColor等)时,UILabel会将这些字母显示为白色。 以下是我的代码行。

[attributedString addAttribute:NSForegroundColorAttributeName
                         value:[UIColor colorWithRed:66
                                               green:79
                                                blue:91
                                               alpha:1]
                         range:NSMakeRange(0, attributedString.length)];
我尝试使用核心图像框架中的 CIColor 来制作颜色,但结果相同。我应该在代码中做哪些改变才能正确执行呢?
谢谢大家的回答!
5个回答

121

你的值不正确,需要将每个颜色值除以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

参数

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

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

blue 颜色对象的蓝色分量,指定为0.0到1.0之间的值。

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

请参考此处。


1
它运行得很好,现在我因为这样的错误感觉像个白痴!谢谢! - agoncharov
UIColor中有两个新方法可以接受0到255之间的整数值。请查看我的答案:https://dev59.com/Ym035IYBdhLWcg3wE7xr#58124535 - Blip

29

我最喜欢的宏之一,没有它就没有项目:

#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]

使用 like:

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

请问是针对Swift编程语言的吗? - Jaswanth Kumar
1
嗨,@JaswanthKumar,请查看我关于 Swift 版本的答案。 - superarts.org

5

UIColor 使用的范围是从 0 到 1.0,而不是 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)];

4
请尝试这段代码。
[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)];

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

UIColor的RGB分量是在0到1之间进行缩放的,而不是最大值为255。


4

由于 @Jaswanth Kumar 的要求,这里是来自 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)
        )
    }
}

Usage: let color = UIColor(rgb: 0x112233)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接