Hex transparency in colors

Hex transparency in colors

技术背景

在前端开发和图形处理中,颜色的表示和透明度的设置是常见需求。十六进制颜色编码是一种广泛使用的颜色表示方法,而透明度也可以用十六进制值来表示。了解如何将透明度百分比转换为十六进制值,以及如何进行反向转换,对于精确控制颜色和透明度非常重要。

实现步骤

透明度百分比与十六进制值的对应表

%Hex
100%FF
95%F2
90%E6
85%D9
80%CC
75%BF
70%B3
65%A6
60%99
55%8C
50%80
45%73
40%66
35%59
30%4D
25%40
20%33
15%26
10%1A
5%0D
0%00

手动计算转换方法

百分比转十六进制值

  1. 计算十进制值:decimal = percentage * 255 / 100。例如,对于 50%,decimal = 50 * 255 / 100 = 127.5
  2. 将十进制值转换为十六进制值。例如,127.5 转换为十六进制是 7F。

十六进制值转百分比

  1. 将十六进制值转换为十进制值。例如,D6 转换为十进制是 13 * 16^1 + 6 = 214
  2. 计算百分比:percentage = (value in decimal) * 100 / 255。例如,214 的百分比是 214 * 100 / 255 ≈ 84%

核心代码

Java 代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class ColorUtils {
/**
* @param originalColor color, without alpha
* @param alpha from 0.0 to 1.0
* @return
*/
public static String addAlpha(String originalColor, double alpha) {
long alphaFixed = Math.round(alpha * 255);
String alphaHex = Long.toHexString(alphaFixed);
if (alphaHex.length() == 1) {
alphaHex = "0" + alphaHex;
}
originalColor = originalColor.replace("#", "#" + alphaHex);
return originalColor;
}

public static String setColorAlpha(int percentage, String colorCode) {
double decValue = ((double) percentage / 100) * 255;
String rawHexColor = colorCode.replace("#", "");
StringBuilder str = new StringBuilder(rawHexColor);

if (Integer.toHexString((int) decValue).length() == 1) {
str.insert(0, "#0" + Integer.toHexString((int) decValue));
} else {
str.insert(0, "#" + Integer.toHexString((int) decValue));
}
return str.toString();
}
}

SASS 代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
@mixin ie8-rgba ($r, $g, $b, $a) {
$rgba: rgba($r, $g, $b, $a);
$ie8-rgba: ie-hex-str($rgba);
.lt-ie9 & {
background-color: transparent;
filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0, startColorstr='#{$ie8-rgba}', endColorstr='#{$ie8-rgba}');
}
}

.transparent {
@include ie8-rgba(88, 153, 131, .8);
background-color: rgba(88, 153, 131, .8);
}

最佳实践

  • 可以使用在线工具或代码片段来快速进行透明度百分比和十六进制值的转换。
  • 在代码中封装转换方法,方便重复使用。
  • 使用 SASS 等预处理器来简化颜色和透明度的处理。

常见问题

  • Google 搜索转换问题:Google 搜索在转换时不进行四舍五入,只能使用一位小数的乘数。如果要使用如 0.85 这样的值,需要先计算 255 * 0.85 的四舍五入值,再进行转换。
  • 十六进制值长度问题:在将十进制转换为十六进制时,如果结果是一位数,需要补 0 以保证格式正确。例如,3 应表示为 03。