Android int颜色值和rgba颜色互转

有的App后台网络颜色值使用的Android的int类型的颜色值。iOS使用RGBA的颜色值。怎么进行转换呢?

// Swift
func color(_ color: Int) -> UIColor {
    let c: UInt32 = UInt32(color)
    let alpha = CGFloat(c >> 24) / 255.0
    let r = CGFloat((c & 0xff0000) >> 16) / 255.0
    let g = CGFloat((c & 0xff00) >> 8) / 255.0
    let b = CGFloat(c & 0xff) / 255.0
    return UIColor.init(red: r, green: g, blue: b, alpha: alpha)
}
// Swift
func intColor(_ color: UIColor) -> Int {
    let alpha: UInt32 =
    ... 省略从UIColor获取r,g,b,alpha的代码
    let intColor: UInt32 = (alpha << 24) | (r << 16) | (g << 8) | b;
    return Int(intColor);
}

注意:Android没有无符号整数,在获取alpha值的时候,要使用算术右移。示例如下:

// Java
void printRGBA(int color) {
    int alpha = color >>> 24;
    int r = ( color & 0xff0000 ) >> 16;
    int g = ( color & 0xff00 ) >> 8;
    int b = color & 0xff;
    System.out.println(alpha + ", " + r + ", " + g + ", " + b);
}

你可能感兴趣的:(Android int颜色值和rgba颜色互转)