代码之家  ›  专栏  ›  技术社区  ›  Javier P

带有圆角和多种颜色的进度条

  •  1
  • Javier P  · 技术社区  · 7 年前

    我已经读过类似的问题 here here 如果您只想显示带有圆角的单个进度条,那么这是很好的解决方案,但在我的示例中,我想显示由多个“子进度”颜色组成的进度,如下图所示:

    progress bar

    到目前为止,我所做的是编写这样的线性梯度实现 answer 但它在角落里看起来是方形的。

    我怎样才能取得这样的进展?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Javier P    7 年前

    经过一些研究,我发现这个班 PaintDrawable 我可以将其设置为任何视图的背景,令人惊讶的是,我可以为这个可绘制的设置一个形状,所以如果我使用 RoudRectShape 它看起来像我想要的那样圆润,我的最终代码如下:

            // mRatios is a View
            ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
                @Override
                public Shader resize(int i, int i1) {
                    LinearGradient lg = new LinearGradient(0, 0, mRatios.getWidth(), 0,
                            barColorsArray,
                            barRatiosArray,
                            Shader.TileMode.REPEAT);
    
                    return lg;
                }
            };
            PaintDrawable paintDrawable = new PaintDrawable();
    
            // not sure how to calculate the values here, but it works with these constants in my case
            paintDrawable.setShape(new RoundRectShape(new float[]{100,100,100,100,100,100,100,100}, null, null));
            paintDrawable.setShaderFactory(sf);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                mRatios.setBackgroundDrawable(paintDrawable);
            } else {
                mRatios.setBackground(paintDrawable);
            }