Custom Rounded Slider with thumb in Compose

If you have worked with material design and you wanted to change the thumb for some reason it was hard to do it. We mostly used third party libs which would help us customize the slider. https://github.com/material-components/material-components-android/issues/935

So in compose its easier to change the underlying code by coping the compose source code. The source code to the same https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/material/material/src/commonMain/kotlin/androidx/compose/material/Slider.kt

        drawLine(
inactiveTrackColor.value,
sliderStart,
sliderEnd,
trackStrokeWidth,
StrokeCap.Butt
)

The above code is from the composable Track. They are drawing active an inactive lines.

Since we want to rounded rectangle we will draw the same.

drawRoundRect(
color = inactiveTrackColor.value,
topLeft = Offset(sliderStart.x / 2, rectY),
size = Size(width = sliderEnd.x, height = TrackHeight.toPx()),
cornerRadius = CornerRadius(5.dp.toPx(), 5.dp.toPx()),
)

The same goes for the active part as well

drawRoundRect(
color = activeTrackColor.value,
topLeft = Offset(sliderStart.x / 2, rectY),
size = Size(width = sliderValue.x, height = TrackHeight.toPx()),
cornerRadius = CornerRadius(5.dp.toPx(), 5.dp.toPx()),
)

Now we have drawn the rectangles in place. Next step is to add the drawable as thumb.

If you look at the SliderImpl there is a box composable and a surface as child. All you need to do is add a Image Composable

Image(
painter = painterResource(R.drawable.thumb),
contentDescription = "Thumb",
modifier = Modifier
.size(thumbSize, thumbSize)
.align(Alignment.Center),
contentScale = ContentScale.FillWidth
)

That’s it. And the result

Conclusion : We can copy the source code of composables analyze and modify it to suit our design needs.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store