为自定义 seekBar 动态更改 LinearGradient 颜色比率

change LinearGradient colors ratio dynamically for custom seekBar

我创建了一个带有自定义 LinearGradient 可绘制对象的搜索栏。但是,我希望能够改变每种颜色的渐变比例,这里我使用了 3 种颜色,如果 positionsnull,它们会均匀分布。事实上,我想要的是为每种颜色提供宽度或比例,例如更改红色比例并将其设置为仅从 0% 到 10% of seekBar width.

这里我想设置 0% 到 10% 红色、10% - 80% 黄色和 80% 到 100% 红色,并且能够动态更改每种颜色的宽度值。

这可能吗?如果可以,谁能指导我怎么做?

我的代码

private ShapeDrawable getSeekBarGradientDrawable(int mRectWidth, int mRectHeight) {
    int[] colors = new int[] { Color.RED, Color.YELLOW, getResources().getColor(R.color.primaryButton, null)};

DisplayMetrics displayMetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int width = displayMetrics.widthPixels - (int) getResources().getDimension(R.dimen.margin_padding_size_medium);

    Shader shader = new LinearGradient(
            0,
            0,
            width,
            mRectHeight,
            colors, new float[] {0.1f,0.7f,0.2f},
            Shader.TileMode.CLAMP);

    ShapeDrawable shape = new ShapeDrawable(new RectShape());
    shape.getPaint().setShader(shader);
    return shape;
}

当前设置可以看到图片,和我描述的不一样

此答案适用于使用 LinearGradient 作为 Shader

通过如下设置 colors 数组,将 LinearGradient 颜色从一种颜色过渡到相同颜色:

int[] colors = new int[]{Color.RED, Color.RED, Color.YELLOW, Color.YELLOW, Color.GREEN, Color.GREEN};

更改 LinearGradient 以定义颜色区域,如下所示:参见 LinearGradient with positions

Shader shader = new LinearGradient(  
    0,  
    0,  
    width,  
    mRectHeight,  
    colors, new float[]{0f, 0.1f, 0.1f, 0.8f, 0.8f, 1.0f},  
    Shader.TileMode.CLAMP);

这会强制 着色器 在一个区域上从一种颜色过渡到相同的颜色,从而创建纯色。

以上将提供从一种颜色到另一种颜色的即时过渡。如果你想要一个窄过渡(比 LinearGradient 的默认值更窄),你可以按如下方式操作颜色和位置数组。下面,我们将过渡从红色更改为黄色。

int[] colors = new int[]{Color.RED, Color.RED, Color.YELLOW, Color.YELLOW, Color.YELLOW, Color.GREEN, Color.GREEN};
Shader shader = new LinearGradient(
        0,
        0,
        width,
        mRectHeight,
        colors, new float[]{0f, 0.1f, 0.15f, 0.15f, 0.8f, 0.8f, 1.0f},
        Shader.TileMode.CLAMP);