2

我在数据库中有几行,其中一个字段是相关颜色的 ARGB 值。

我必须读取这些表的所有行并将 ARGB 值十进制转换为 UIColor。

我用谷歌搜索找到了这个,但我没有。

有没有办法解决这个问题?

谢谢。

4

4 回答 4

13

这是我想出的将 ARGB 整数转换为 UI 颜色的方法。用我们的 .NET 系统中的几种颜色对其进行了测试

+(UIColor *)colorFromARGB:(int)argb {
    int blue = argb & 0xff;
    int green = argb >> 8 & 0xff;
    int red = argb >> 16 & 0xff;
    int alpha = argb >> 24 & 0xff;

    return [UIColor colorWithRed:red/255.f green:green/255.f blue:blue/255.f alpha:alpha/255.f];
}
于 2012-05-18T18:07:51.353 回答
2
text.color = [UIColor colorWithRed:10.0/255.0 green:100.0/255.0 blue:55.0/255.0 alpha:1];

您只需将 RGB 值除以 255 即可正确设置。

于 2012-02-24T16:54:44.027 回答
1

您可以定义一个宏并在整个代码中使用它

#define UIColorFromARGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0xFF))/255.0 alpha:((float)((rgbValue & 0xFF000000) >> 24))/255.0]
于 2015-08-12T08:28:31.513 回答
0

现在是 2021 年,我们都在使用 Swift ;) 所以这里有一个 Swift 扩展来解决这个问题:

extension UIColor {

    /* Converts an AARRGGBB into a UIColor like Android Color.parseColor */
    convenience init?(hexaARGB: String) {
        var chars = Array(hexaARGB.hasPrefix("#") ? hexaARGB.dropFirst() : hexaARGB[...])
        switch chars.count {
        case 3: chars = chars.flatMap { [$0, $0] }; fallthrough
        case 6: chars.append(contentsOf: ["F","F"])
        case 8: break
        default: return nil
        }
        self.init(red: .init(strtoul(String(chars[2...3]), nil, 16)) / 255,
                green: .init(strtoul(String(chars[4...5]), nil, 16)) / 255,
                 blue: .init(strtoul(String(chars[6...7]), nil, 16)) / 255,
                alpha: .init(strtoul(String(chars[0...1]), nil, 16)) / 255)
    }
}

用法

UIColor(hexaARGB: "#CCFCD204")
于 2021-12-14T16:07:07.987 回答