2016-05-29 215 views
2

我正在嘗試創建一個圓角方形線條進度條來繪製圖像周圍的進度。Android - 圓角方形線條進度條

enter image description here

到目前爲止,我有以下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合併期間考慮了所有像素。但結果相同。

+0

創建自定義'調用'時將使用Drawable'類setProgressDrawable' – pskink

+0

@ pskink,是的,謝謝,但如何在線上繪製正確的進度效果? – Bibu

+0

您是否創建了自定義Drawable類?什麼問題你有什麼時候繪製輪迴? – pskink

回答

3

試試這個簡單的自定義類:

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);