2012-11-04 99 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)