Skip to content

Instantly share code, notes, and snippets.

@ChrisMCMine
Created May 23, 2015 17:11
Show Gist options
  • Save ChrisMCMine/4b1a12105e5f0edf2703 to your computer and use it in GitHub Desktop.
Save ChrisMCMine/4b1a12105e5f0edf2703 to your computer and use it in GitHub Desktop.
Convert a String with Minecraft color codes (http://minecraft.gamepedia.com/Formatting_codes) to its html representation using <font color=...
private ArrayList<Pair<Integer, Character>> getColorCodes() {
ArrayList<Pair<Integer, Character>> colorCodes = new ArrayList<>();
colorCodes.add(new Pair<>(0x000000, '0'));
colorCodes.add(new Pair<>(0x0000AA, '1'));
colorCodes.add(new Pair<>(0x00AA00, '2'));
colorCodes.add(new Pair<>(0x00AAAA, '3'));
colorCodes.add(new Pair<>(0xAA0000, '4'));
colorCodes.add(new Pair<>(0xAA00AA, '5'));
colorCodes.add(new Pair<>(0xFFAA00, '6'));
colorCodes.add(new Pair<>(0xAAAAAA, '7'));
colorCodes.add(new Pair<>(0x555555, '8'));
colorCodes.add(new Pair<>(0x5555FF, '9'));
colorCodes.add(new Pair<>(0x55FF55, 'a'));
colorCodes.add(new Pair<>(0x55FFFF, 'b'));
colorCodes.add(new Pair<>(0xFF5555, 'c'));
colorCodes.add(new Pair<>(0xFF55FF, 'd'));
colorCodes.add(new Pair<>(0xFFFF55, 'e'));
colorCodes.add(new Pair<>(0xFFFFFF, 'f'));
return colorCodes;
}
private CharSequence toHtml(String s) {
// replace all \u00A7 color codes with their hex representation
for (Pair<Integer, Character> colorCode : getColorCodes()) {
s = s.replace("\u00A7" + colorCode.second, "</font><font color=\"" + colorCode.first + "\">");
}
return Html.fromHtml("<font>" + s + "</font>");
}
@ChrisMCMine
Copy link
Author

Note that this will only work on android because some android only classes are used (android.text.Html and android.util.Pair)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment