java 计算任意字符串的十六进制颜色代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2464745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 21:18:17  来源:igfitidea点击:

Compute hex color code for an arbitrary string

javarubycolorshex

提问by tech20nn

Heading

标题

Is there a way to map an arbitrary string to a HEX COLOR code. I tried to compute the HEX number for string using string hashcode. Now I need to convert this hex number to six digits which are in HEX color code range. Any suggestions ?

有没有办法将任意字符串映射到十六进制颜色代码。我尝试使用字符串哈希码计算字符串的十六进制数。现在我需要将此十六进制数转换为十六进制颜色代码范围内的六位数字。有什么建议 ?

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()));
}

回答by M. Jessup

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)

如果您真的不关心颜色的“含义”,您可以将 int 的位分开(删除第一个仅用于 RGB 而不是 ARGB)

String [] programs = {"XYZ", "TEST1", "TEST2", "TEST3", "SDFSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"};

for(int i = 0; i < programs.length; i++) {
  System.out.println( programs[i] + " -- " + intToARGB(programs[i].hashCode()));
}
....
public static String intToARGB(int i){
    return Integer.toHexString(((i>>24)&0xFF))+
        Integer.toHexString(((i>>16)&0xFF))+
        Integer.toHexString(((i>>8)&0xFF))+
        Integer.toHexString((i&0xFF));
}

回答by codaddict

How about anding the hashcodewith 0x00FFFFFF

hashcode与一起怎么样0x00FFFFFF

回答by NealJMD

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.hashand the optional base-specifying parameter of Fixnum.to_s. It slices from 1rather than 0to skip negative signs.

我在寻找 Ruby 解决方案时遇到了这个问题,所以我想我会为 Ruby 添加一个答案,以防有人遵循我所做的相同路径。我结束了使用以下的方法,其中从通过使用一个字符串创建相同的六位十六进制代码String.hash和可选的基极-指定参数Fixnum.to_s。它从而1不是0跳过负号切片。

def color_from_string(query)
  '#'+query.hash.to_s(16).slice(1,6)
end