获取过度颜色百分比及设置背景颜色渐变

来源:互联网 发布:靠谱泰国代购淘宝 知乎 编辑:程序博客网 时间:2024/05/18 17:41

1.设置背景颜色渐变

/背景色渐变    public  void changebackgroud(int color1, int color2){        GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{color1, color2});        drawerlayout.setBackground(gd);    }

2.获取渐变色百分比(网上找的)

public class ChangeColor {    /**     * 计算从startColor过度到endColor过程中百分比为franch时的颜色值     * @param startColor 起始颜色 int类型     * @param endColor 结束颜色 int类型     * @param franch franch 百分比0.5     * @return 返回int格式的color     */    public static int caculateColor(int startColor, int endColor, float franch){        String strStartColor = "#" + Integer.toHexString(startColor);        String strEndColor = "#" + Integer.toHexString(endColor);        return Color.parseColor(caculateColor(strStartColor, strEndColor, franch));    }    /**     * 计算从startColor过度到endColor过程中百分比为franch时的颜色值     * @param startColor 起始颜色 (格式#FFFFFFFF)     * @param endColor 结束颜色 (格式#FFFFFFFF)     * @param franch 百分比0.5     * @return 返回String格式的color(格式#FFFFFFFF)     */    public static String caculateColor(String startColor, String endColor, float franch){        int startAlpha = Integer.parseInt(startColor.substring(1, 3), 16);        int startRed = Integer.parseInt(startColor.substring(3, 5), 16);        int startGreen = Integer.parseInt(startColor.substring(5, 7), 16);        int startBlue = Integer.parseInt(startColor.substring(7), 16);        int endAlpha = Integer.parseInt(endColor.substring(1, 3), 16);        int endRed = Integer.parseInt(endColor.substring(3, 5), 16);        int endGreen = Integer.parseInt(endColor.substring(5, 7), 16);        int endBlue = Integer.parseInt(endColor.substring(7), 16);        int currentAlpha = (int) ((endAlpha - startAlpha) * franch + startAlpha);        int currentRed = (int) ((endRed - startRed) * franch + startRed);        int currentGreen = (int) ((endGreen - startGreen) * franch + startGreen);        int currentBlue = (int) ((endBlue - startBlue) * franch + startBlue);        return "#" + getHexString(currentAlpha) + getHexString(currentRed)                + getHexString(currentGreen) + getHexString(currentBlue);    }    /**     * 将10进制颜色值转换成16进制。     */    public static String getHexString(int value) {        String hexString = Integer.toHexString(value);        if (hexString.length() == 1) {            hexString = "0" + hexString;        }        return hexString;    }}

我使用的时候配合了主题框架颜色的改变效果不错