What are the ways to programmatically generate Material Design color sets?

前端 未结 2 1338
栀梦
栀梦 2021-02-07 22:04

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

2条回答
  •  情书的邮戳
    2021-02-07 23:05

    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).

提交回复
热议问题