I am trying to create a colour palette of Material Design that changing the lightness / luminosity by percentage with arbitrary color hex. When it comes to the implementation, I
The problem is in the following lines:
int resultColorInt = Color.HSVToColor(alpha, new float[] { h, s, v });
return Integer.toHexString(resultColorInt).toUpperCase();
When alpha value is less than 16 (0xF0), it will occupy only one char in the string:
// 1-char alpha
int resultColorInt = Color.HSVToColor(1, new float[]{340, 0.7f, 0.5f});
String result = Integer.toHexString(resultColorInt).toUpperCase();
// result == "1802644" - 7 chars, which is invalid color format
You need to compensate 1-char or 0-char alphas (in range 0-15) by appending 0 at the beginning of the resulting string:
// not the best code, but works
while (result.length() < 8) {
result = "0" + result;
}
// don't forget # to make it a legal color
result = "#" + result;
return result;
However, the best thing would be to avoid strings altogether. Use ints instead - they contain the same data with better performance. For your convenience, in debugger you can change ints to be displayed in HEX, instead of DEC (in Android Studio: right click in Variables view, View as -> HEX).