Using color and color.darker in Android?

后端 未结 4 1758
傲寒
傲寒 2020-12-02 09:07

Okay, so I have an integer variable in my application. It\'s the value of a color, being set by a color picker in my preferences. Now, I need to use both that color and a da

4条回答
  •  执笔经年
    2020-12-02 09:33

    The easiest, I think, would be to convert to HSV, do the darkening there, and convert back:

    float[] hsv = new float[3];
    int color = getColor();
    Color.colorToHSV(color, hsv);
    hsv[2] *= 0.8f; // value component
    color = Color.HSVToColor(hsv);
    

    To lighten, a simple approach may be to multiply the value component by something > 1.0. However, you'll have to clamp the result to the range [0.0, 1.0]. Also, simply multiplying isn't going to lighten black.

    Therefore a better solution is: Reduce the difference from 1.0 of the value component to lighten:

    hsv[2] = 1.0f - 0.8f * (1.0f - hsv[2]);
    

    This is entirely parallel to the approach for darkening, just using 1 as the origin instead of 0. It works to lighten any color (even black) and doesn't need any clamping. It could be simplified to:

    hsv[2] = 0.2f + 0.8f * hsv[2];
    

    However, because of possible rounding effects of floating point arithmetic, I'd be concerned that the result might exceed 1.0f (by perhaps one bit). Better to stick to the slightly more complicated formula.

提交回复
热议问题