Draw custom Seekbar on Android

2019-09-21 19:17发布

问题:

I know there are a lot of libraries about that on GitHub and several questions on stack overflow about this argument. But no of those fit my needs.

I just need to draw something like this :

The progress line must be yellow with no thumb.

Thank you in advance.

回答1:

You can use something similar to what I explained here.

Just use a rectangle instead of a circle. Use on-size changed to compute the actual size of the rectangle and have a method to change the percentage and re-compute your rectangle size / recreate your path.

When you change the path you just have to call invalidate() to cause a re-draw.

Pseudo code:

public void setProgress(float progress) {
    this.progress = progress;
    refreshProgressBar();
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    this.currentW = w;
    this.currentH = h;
    refreshProgressBar();
}

private void refreshProgressBar() {
    path.reset();
    // build your clipping path using progress / currentW / currentH
    path.close();
    invalidate();
}

You can do all with a single custom view or have 2 views on top of each other, the one containing the "fill" of the bar is clipped with the method I explained above.

Keep in mind the clipping happens on the Canvas. So if you you use a custom View just set the clipping before drawing the progress view and remove it when you are done (you can also directly draw the color in this case - but if you have a complex color pattern it may be easier to clip). If you use a clipping ViewGroup like in the link I gave you you'll have to build your layout accordingly so that the clipped view is only the progress one.

If you play a bit with math you may also be able to draw a path that match your art work and use it on a full color rectangle on top of your layout.

If you add together a Rectangle and a circle and then remove a circle (use the OP for adding / subtracting / multiplicating on the path) you should obtain a Path (shape) that resemble the one in your hand-drawing.

Good Luck.



回答2:

You should create a view for this. Take a look at Android creating custom view

Also, a more easy solution i can think of is to create a rectangular progress bar that occupes the whole width and draw on top on the middle, the play button