Compute hex color code for an arbitrary string
Solution 1
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)
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));
}
Solution 2
How about and
ing the hashcode
with 0x00FFFFFF
(or 0xFFFFFF
if you want to default the alpha channel)? For example:
private String getColorCode(String inputString)
{
String colorCode = String.format("#%06x", 0xFFFFFF & inputString.hashCode());
}
Solution 3
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 of Fixnum.to_s
. It slices from 1
rather than 0
to skip negative signs.
def color_from_string(query)
'#'+query.hash.to_s(16).slice(1,6)
end
Solution 4
In case anyone else is looking for a solution for Flutter/Dart:
Color _fromInt(int i) {
final a = (i >> 24) & 0xFF;
final r = (i >> 16) & 0xFF;
final g = (i >> 8) & 0xFF;
final b = i & 0xFF;
return Color.fromARGB(a, r, g, b);
}
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:
Color _fromInt(int i) {
const a = 255;
final r = (i >> 16) & 0xFF;
final g = (i >> 8) & 0xFF;
final b = i & 0xFF;
return Color.fromARGB(a, r, g, b);
}
tech20nn
Updated on June 16, 2022Comments
-
tech20nn almost 2 years
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())); }