【问题标题】:change LinearGradient colors ratio dynamically for custom seekBar为自定义 seekBar 动态更改 LinearGradient 颜色比例
【发布时间】:2021-01-29 20:04:13
【问题描述】:

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

在这里,我想设置 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;
}

图像可以从当前设置中看到,它与我描述的不同。

【问题讨论】:

    标签: java android material-design android-seekbar android-graphics


    【解决方案1】:

    此答案适用于使用 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);
    

    【讨论】:

    • 谢谢@Cheticamp,感谢您的帮助。我需要支持低于 29 的 api 级别。通过自定义 drawable,您指的是 xml drawables 吗?我调查了一下,也不确定我是否能够动态更新它。我会详细看的。谢谢
    • 是的,我刚刚签入了 api 级别 28,它正在工作。但有一件事,颜色没有在当前版本中混合。研究在边缘实现颜色的平滑混合,我会接受你的回答。谢谢你:)
    • @AmirDora.我不明白你的最后评论。您是说您不想从一种颜色立即过渡到另一种颜色,而是希望有一个狭窄的过渡?
    • 是的,完全是@Cheticamp,遗憾的是我找不到任何关于它的文档。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多