Search code examples
androidcolorsandroid-color

Android: Compute color dynamically


I have a Util class which is capable of creating color codes(decimal).

public class ColorUtils {

    private static final String RED = "ff0000";
    private static final String GREEN = "00ff00";
    private static final String BLUE = "0000ff";
    private static final String WHITE = "ffffff";
    private static final int RADIX = 16;

    public static int getColorShade(String deepShade, String lightShade, float percentage) {
        if (percentage > 100) {
            throw new RuntimeException("Percentage can not be more than 100");
        }
        int deepShadeCode = Integer.parseInt(deepShade, RADIX);
        int lightShadeCode = Integer.parseInt(lightShade, RADIX);
        int shadeDifference = deepShadeCode - lightShadeCode;
        int shadeOffset = (int) (shadeDifference * percentage)/100;
        return lightShadeCode + shadeOffset;
    }

    public static int getColorShade(String deepShade, float percentage) {
        return getColorShade(deepShade, WHITE, percentage);
    }

    public static int getRedColorShade(float percentage) {
        return getColorShade(RED, percentage);
    }

    public static int getGreenColorShade(float percentage) {
        return getColorShade(GREEN, percentage);
    }

    public static int getBlueColorShade(float percentage) {
        return getColorShade(BLUE, percentage);
    }

    public static int getWhite() {
        return Integer.parseInt(WHITE, RADIX);
    }
}

Is there any way to convert it to Android color? All I could find out is ContextCompat.getColor(this,R.color.yourcolor) but this will take resource id in second arguments, I don't want to make color pallets in color.xml. Is there a work around?


Solution

  • Don't know how you create the color, but if it can extract red, green, blue, then try this:

    @ColorInt int color = Color.rgb(getRedColorShade(percentage), getGreenColorShade(percentage), getBlueColorShade(percentage));
    

    Ref here, this time it's pretty sure that this method is added from API level 1 and can be used instead of valueOf