如何从RGBA创建UIColor?

时间:2012-11-04 23:48:53

标签: ios objective-c rgb nsattributedstring uicolor

我想在我的项目中使用NSAttributedString,但是当我尝试设置颜色时,不是来自标准集(redColorblackColor,{{1等等)greenColor以白色显示这些字母。 这是我的代码行。

UILabel

我尝试使用Core Image框架中的[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:66 green:79 blue:91 alpha:1] range:NSMakeRange(0, attributedString.length)]; 制作颜色,但它显示了相同的结果。 我应该如何更改代码以正确的方式执行它?

谢谢答案,伙计们!

5 个答案:

答案 0 :(得分:111)

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

<强>阿尔法 颜色对象的不透明度值,指定为0.0到1.0之间的值。

Reference here.

答案 1 :(得分:27)

我最喜欢的一个宏,没有项目没有:

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

答案 2 :(得分: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)];

答案 3 :(得分:3)

请尝试代码

[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 :(得分:3)

自@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)
        )
    }
}

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