背景
服务端下发的颜色值字符串由于一开始依据 iOS 端的 RGBA 格式,Android 端(Android 使用 ARGB 方式)需要进行兼容,需要对此字符串转换。
举例:RGBA #ABCDEF99
=> ARGB #99ABCDEF
String argbStr = rgba.substring(0, 1) + rgba.substring(7, 9) + rgba.substring(1, 7);
int argb = Color.parseColor(argbStr);
char[] chars = rgba.toCharArray();
StringBuilder tempStr = new StringBuilder();
for (int i = 0; i < chars.length; i++) {
if (i == 0) {
tempStr.append(chars[0]);
} else if (i == 1) {
tempStr.append(chars[7]);
} else if (i == 2) {
tempStr.append(chars[8]);
} else {
tempStr.append(chars[i - 2]);
}
}
int argb = Color.parseColor(tempStr.toString());
int rgba = Color.parseColor(rgbaStr);
int argb = (rgba >>> 8) | (rgba << (32 - 8));
注意事项:
rgbaStr
字符的长度为 9 的时候,才需要转换,7 位时只有RGB色值,直接使用 Color.parseColor()
即可。
Color.parseColor()
使用注意事项:
IllegalArgumentException
的异常,使用时可以进行一层封装,对异常进行捕获并记录日志,出现异常时返回一个预设的颜色值。以下算法临时改写而成,未经实际产品应用,建议先跑一些测试用例进行验证。
// 1. 字符串截取+拼接
String argbTemp= argbStr.substring(0, 1) + argbStr.substring(3, 9) + argbStr.substring(1, 3);
int rgba = Color.parseColor(argbTemp);
// 2. 转为Char数组,遍历重组
char[] chars = argbStr.toCharArray();
StringBuilder tempStr = new StringBuilder();
for (int i = 0; i < chars.length; i++) {
if (i == 0) {
tempStr.append(chars[0]);
} else if (i == 7) {
tempStr.append(chars[1]);
} else if (i == 8) {
tempStr.append(chars[2]);
} else {
tempStr.append(chars[i + 2]);
}
}
int rgba = Color.parseColor(tempStr.toString());
// 3. 位操作
int argb = Color.parseColor(argbStr);
int rgba = (argb << 8) | (argb >>> (32-8));