2012-08-09 117 views
12

我有一個項目,我需要將UIColor的RGBA值作爲8字符的十六進制字符串存儲在數據庫中。例如,[UIColor blueColor]將是@「0000FFFF」。 我知道我能得到像這樣的元件值:如何將UIColor轉換爲十六進制字符串?

CGFloat r,g,b,a; 
[color getRed:&r green:&g blue: &b alpha: &a]; 

,但我不知道如何從這些值到十六進制字符串。我已經看到了很多關於如何去其他方式的帖子,但是這種轉換沒有任何功能。

回答

21

讓您的花車轉換爲第一int類型,然後用stringWithFormat格式:

int r,g,b,a; 

    r = (int)(255.0 * rFloat); 
    g = (int)(255.0 * gFloat); 
    b = (int)(255.0 * bFloat); 
    a = (int)(255.0 * aFloat); 

    [NSString stringWithFormat:@"%02x%02x%02x%02x", r, g, b, a]; 
+0

我試過以前的建議,但此實際工作。 – 2012-08-09 13:23:14

+0

方法getRed:綠色:藍色:alpha:僅適用於iOS 5+。關於iOS 4呢? – VietHung 2013-10-02 07:00:36

+1

可以在這裏找到一個反向轉換的好方法(比如如果你要從數據庫/核心數據存儲/加載顏色) - http://stackoverflow.com/a/12397366/553394 – 2014-03-01 01:04:48

14

在這裏不言而喻。返回一個帶有十六進制顏色值的NSString(例如ffa5678)。

- (NSString *)hexStringFromColor:(UIColor *)color 
{ 
    const CGFloat *components = CGColorGetComponents(color.CGColor); 

    CGFloat r = components[0]; 
    CGFloat g = components[1]; 
    CGFloat b = components[2]; 

    return [NSString stringWithFormat:@"%02lX%02lX%02lX", 
      lroundf(r * 255), 
      lroundf(g * 255), 
      lroundf(b * 255)]; 
} 
+0

用'[UIColor grayColor]'(或任何其他非RGB顏色)嘗試此操作。糟糕的結果或可能的崩潰! – rmaddy 2015-01-23 17:31:59

相關問題