根据字符串生成固定颜色,效果如下
算法来自 python 根据字符串随机生成颜色 , 这里简单用 go 改写
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
func str2rgb(text string) string {
s384 := sha512.New384()
s384.Write([]byte(text))
digest := hex.EncodeToString(s384.Sum(nil))
subSize := len(digest) / 3
mv := big.NewInt(math.MaxInt64)
mv.SetString(strings.Repeat("f", subSize), 16)
maxValue := big.NewFloat(math.MaxFloat64)
maxValue.SetInt(mv)
digests := make([]string, 3)
for i := 0; i < 3; i++ {
digests[i] = digest[i*subSize : (i+1)*subSize]
}
goldPoint := big.NewFloat(0.618033988749895)
rgbLst := make([]string, 3)
for i, v := range digests {
in := big.NewInt(math.MaxInt64)
in.SetString(v, 16)
inv := big.NewFloat(math.MaxFloat64)
inv.SetInt(in)
inf := big.NewFloat(math.MaxFloat64)
inf.Quo(inv, maxValue).Add(inf, goldPoint)
oneFloat := big.NewFloat(1)
cmp := inf.Cmp(oneFloat)
if cmp > -1 {
inf.Sub(inf, oneFloat)
}
inf.Mul(inf, big.NewFloat(255)).Add(inf, big.NewFloat(0.5)).Sub(inf, big.NewFloat(0.0000005))
i64, _ := inf.Int64()
//fmt.Println(i64)
rgbLst[i] = strconv.FormatInt(i64, 16)
}
return strings.Join(rgbLst, "")
}
本文网址: https://golangnote.com/topic/275.html 转摘请注明来源