问题
I am trying to create custom seek bar in android with multicolor. I tried below code
customseekbar.java
int proBarWidth = getWidth();
int proBarHeight = getHeight();
int thumboffset = getThumbOffset();
int lastproX = 0;
int proItemWidth, proItemRight;
for (int i = 0; i < mproItemsList.size(); i++) {
proItem proItem = mproItemsList.get(i);
Paint proPaint = new Paint();
proPaint.setColor(getResources().getColor(proItem.color));
proItemWidth = (int) (proItem.proItemPercentage
* proBarWidth / 100);
proItemRight = lastproX + proItemWidth;
// for last item give right of the pro item to width of the
// pro bar
if (i == mproItemsList.size() - 1
&& proItemRight != proBarWidth) {
proItemRight = proBarWidth;
}
Rect proRect = new Rect();
proRect.set(lastproX, thumboffset / 2, proItemRight,
proBarHeight - thumboffset / 2);
canvas.drawRect(proRect, proPaint);
lastproX = proItemRight;
}
super.onDraw(canvas);
view
<mypackage.customseekbar
android:id="@+id/customseekbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="0"
android:progressDrawable="@android:color/transparent"
android:thumb="@drawable/seek_thumb_normal"
android:thumbOffset="12dp" />
I used this method in MainMenuActivity
. It gives me result something like below. I referred this link https://azzits.wordpress.com/2013/11/17/customseekbar/
But I am expecting something like below
Is there any way to draw this vertical gapped lines? How can I draw this vertical lines?
回答1:
Progress bar with divider is a good place to look as mentioned by @Nilesh Rathod. Rather than using canvas.drawRect() you can use canvas.drawRoundRect(); Short example:
for (int i = 0; i < NUM_SEGMENTS; i++) {
float loLevel = i / (float) NUM_SEGMENTS;
float hiLevel = (i + 1) / (float) NUM_SEGMENTS;
if (loLevel <= level && level <= hiLevel) {
float middle = mSegment.left + NUM_SEGMENTS * segmentWidth * (level - loLevel);
canvas.drawRoundRect(mSegment.left, mSegment.top, middle, mSegment.bottom, mPaint);
mPaint.setColor(mBackground);
canvas.drawRoundRect(middle, mSegment.top, mSegment.right, mSegment.bottom, mPaint);
} else {
canvas.drawRoundRect(mSegment, mPaint);
}
mSegment.offset(mSegment.width() + gapWidth, 0);
}
I give full credit to the code above to the creator of the aforementioned link and don't claim any of it as mine as I am just illustrating the change that should be made to reach the desired effect. Please let me know if you run into further issues.
来源:https://stackoverflow.com/questions/50061970/custom-seekbar-with-multi-color