Android - 圆角方形线条进度条

Android - Rounded square line progress bar

我正在尝试创建一个圆角方形线进度条来围绕图像绘制进度。

到目前为止,我有以下 XML 定义了我的圆角方形线:

<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <stroke
        android:width="6dp"
        android:color="@android:color/holo_green_light" />

    <padding
        android:left="5dp"
        android:right="5dp"
        android:bottom="5dp"
        android:top="5dp" />

    <corners android:radius="50dp" />

</shape>

我知道这个解决方案:https://github.com/mrwonderman/android-square-progressbar但我不感兴趣,因为效果不是我想要的。

我尝试在圆角方形线的顶部创建一个普通的圆圈,并尝试将两者与 PorterDuff 合并,但到目前为止我还无法创建进度条效果。把那个圆画个饼图画进度。

我还尝试以编程方式创建圆角正方形,以防 XML 膨胀被视为普通图像,并且在 PorterDuff 合并期间考虑了所有像素。但结果相同。

试试这个简单的习惯 class:

class V extends View {
    Path path = new Path();
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    float length;
    float[] intervals = {0, 0};

    public V(Context context) {
        super(context);
        paint.setColor(Color.GREEN);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(20);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        path.reset();
        RectF rect = new RectF(0, 0, w, h);
        float inset = paint.getStrokeWidth();
        rect.inset(inset, inset);

        path.addRoundRect(rect, 100, 100, Path.Direction.CW);
        length = new PathMeasure(path, false).getLength();
        intervals[0] = intervals[1] = length;
        PathEffect effect = new DashPathEffect(intervals, length);
        paint.setPathEffect(effect);
    }

    public void setProgress(int progress) {
        PathEffect effect = new DashPathEffect(intervals, length - length * progress / 100);
        paint.setPathEffect(effect);
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawPath(path, paint);
    }
}

测试代码(放在Activity#onCreate里面):

    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);
    SeekBar sb = new SeekBar(this);
    ll.addView(sb);
    final V v = new V(this);
    ll.addView(v);
    setContentView(ll);

    SeekBar.OnSeekBarChangeListener sbcl = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            v.setProgress(progress);
        }
        @Override public void onStartTrackingTouch(SeekBar seekBar) {}
        @Override public void onStopTrackingTouch(SeekBar seekBar) {}
    };
    sb.setOnSeekBarChangeListener(sbcl);