Android: 动态计算颜色

Android: Compute color dynamically

我有一个 Util class 可以创建颜色代码(十进制)。

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);
    }
}

有什么方法可以将其转换为Android颜色吗? 我能找到的只是 ContextCompat.getColor(this,R.color.yourcolor) 但这将在第二个参数中使用资源 ID,我不想在 color.xml 中制作颜色托盘。有解决办法吗?

不知道你是怎么创建颜色的,但是如果它可以提取红色、绿色、蓝色,那么试试这个:

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

Ref here,这次很确定这个方法是从API level 1添加的,可以用来代替valueOf