【问题标题】:Android: Compute color dynamicallyAndroid:动态计算颜色
【发布时间】:2018-05-31 02:23:14
【问题描述】:

我有一个 Util 类,它能够创建颜色代码(十进制)。

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 中制作颜色托盘。有解决办法吗?

【问题讨论】:

  • 是的,现在你做对了。基本上,我的计费软件将具有“总计费金额”和“支付金额”字段。根据总量的比例,我将使用红色阴影作为项目背景。待处理金额越多,背景颜色越深。而我的观点基本上是此类法案的清单。
  • 是的,我终于想通了。它现在按预期工作。无论如何谢谢:)
  • 我废弃了上面的代码并使用 rgb 对其进行了简化

标签: android colors android-color


【解决方案1】:

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

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

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-04-04
  • 2012-07-07
  • 2015-05-09
  • 2013-05-26
  • 1970-01-01
  • 1970-01-01
  • 2013-07-23
  • 2013-01-28
相关资源
最近更新 更多