如何从RGBA创建UIColor?

ago*_*rov 44 rgb objective-c nsattributedstring uicolor ios

我想用NSAttributedString在我的项目,但是当我试图设置颜色,这是不是从标准组(redColor,blackColor,greenColor等)UILabel显示在白色这些信件.这是我的代码行.

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

我尝试使用CIColorCore Image框架制作颜色,但它显示了相同的结果.我应该如何更改代码以正确的方式执行它?

伙计们,谢谢!

yfr*_*cis 113

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

[UIColor colorWithRed:66.0f/255.0f
                green:79.0f/255.0f
                 blue:91.0f/255.0f
                alpha:1.0f];
Run Code Online (Sandbox Code Playgroud)

文档说明:

+ (UIColor *)colorWithRed:(CGFloat)red
                    green:(CGFloat)green
                     blue:(CGFloat)blue
                    alpha:(CGFloat)alpha
Run Code Online (Sandbox Code Playgroud)

参数

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

绿色 颜色对象的绿色组件,指定为0.0到1.0之间的值.

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

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

参考这里.


Ger*_*eri 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]
Run Code Online (Sandbox Code Playgroud)

使用像:

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


cal*_*kus 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)];
Run Code Online (Sandbox Code Playgroud)