試試這個簡單的自定義類:
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);
創建自定義'調用'時將使用Drawable'類setProgressDrawable' – pskink
@ pskink,是的,謝謝,但如何在線上繪製正確的進度效果? – Bibu
您是否創建了自定義Drawable類?什麼問題你有什麼時候繪製輪迴? – pskink