计算任意字符串的十六进制颜色代码
标题
有没有办法将任意字符串映射到十六进制颜色代码。我尝试使用字符串哈希码计算字符串的十六进制数。现在我需要将此十六进制数字转换为十六进制颜色代码范围内的六位数字。有什么建议吗?
String [] programs = {"XYZ", "TEST1", "TEST2", "TEST3", "SDFSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"};
for(int i = 0; i < programs.length; i++) {
System.out.println( programs[i] + " -- " + Integer.toHexString(programs[i].hashCode()));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我在寻找 Ruby 解决方案时遇到了这个问题,所以我想我应该为 Ruby 添加一个答案,以防有人遵循与我相同的路径。我最终使用了以下方法,该方法通过使用
String.hash
以及Fixnum.to_s
。它从1
而不是0
进行切片以跳过负号。I ran into this question while looking for a Ruby solution, so I thought I would add an answer for Ruby in case someone follows the same path I did. I ended up using the following method, which creates the same six digit hex code from a string by using
String.hash
and the optional base-specifying parameter ofFixnum.to_s
. It slices from1
rather than0
to skip negative signs.下面的类接受一个字符串并将其转换为颜色。
它是 Color-Hash TypeScript 项目(MIT 许可证)的简化 Java 端口:https://github。 com/zenozeng/color-hash。
原始项目包含一些参数来调整生成的颜色。
这些不包括在内。
与直接使用哈希值相比,颜色哈希算法的优点是生成的颜色在感知上更加均匀。
这里进行了大量的复制/粘贴:
结果:
The following class takes a String and converts it to a color.
It is a simplified Java port of the Color-Hash TypeScript project (MIT license): https://github.com/zenozeng/color-hash.
The original project contains some parameters to adjust the generated colours.
These were not included.
The advantage of the Color-Hash algorithm, compared using a hash value directly, is that the generated colours are more perceptually uniform.
A lot of copy/paste was going on here:
Result:
如果其他人正在寻找 Flutter/Dart 的解决方案:
还值得注意的是,对于某些背景颜色(例如黑色),可能很难区分颜色。
为此,我将 Alpha 通道设置为最大值 255:
In case anyone else is looking for a solution for Flutter/Dart:
It's also worth noting that with certain background colours e.g. black, it may be difficult to differentiate the colours.
To this end, I set the alpha channel to the max value of 255:
如果你并不真正关心颜色的“含义”,你可以只分割 int 的位(删除第一个仅用于 RGB 而不是 ARGB)
If you don't really care about the "meaning" of the color you can just split up the bits of the int (remove the first for just RGB instead of ARGB)
怎么样
并
使用0x00FFFFFF
(或0xFFFFFF
,如果你想默认alpha通道)来hashcode
?例如:How about
and
ing thehashcode
with0x00FFFFFF
(or0xFFFFFF
if you want to default the alpha channel)? For example: