如何从RGBA创建UIColor?

问题描述 投票:44回答:5

我想在我的项目中使用NSAttributedString,但是当我试图设置颜色时,它不是来自标准集(redColorblackColorgreenColor等).UILabel将这些字母显示为白色。这是我的代码行。

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

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

伙计们,谢谢!

ios objective-c rgb nsattributedstring uicolor
5个回答
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之间的值。

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

Reference here.


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]

使用像:

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

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
投票

请尝试代码

[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。


3
投票

自@Jaswanth Kumar问道,这是来自SwiftLSwift版本:

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)

© www.soinside.com 2019 - 2024. All rights reserved.