dan
07/10/2023, 2:12 AM@Composable
fun Slider(percent: Float, modifier: Modifier = Modifier, onDragEnd:(percent:Float) -> Unit){
var mOffsetX = remember { 0f }
var mWidth = remember { 0 }
var mOffsetInt by remember{ mutableStateOf(0) }
val thumbWidth =with(LocalDensity.current) {14.dp.toPx().toInt()}
LogUtil.i("Slider# percent:$percent")
LaunchedEffect(key1 = percent > 0.0f) {
if(percent > 0.0f && mOffsetInt == 0) {
mOffsetX = mWidth * percent
mOffsetInt = mOffsetX.roundToInt()
}
LogUtil.i("Slider# LaunchedEffect mWidth:$mWidth mOffsetX:$mOffsetX mOffsetInt:$mOffsetInt")
}
Box(modifier = modifier
.onGloballyPositioned { coordinates ->
val width = coordinates.boundsInParent().width
mWidth = width.toInt() - thumbWidth
},
){
Spacer(
modifier = Modifier
.fillMaxWidth()
.height(3.dp)
.align(Alignment.Center)
.background(BaseColor.graySlider, RoundedCornerShape(50))
.drawWithContent {
drawContent()
drawRect(
color = BaseColor.bluePrimary,
size = Size(mOffsetInt.toFloat(), size.height)
)
}
)
Spacer(
modifier = Modifier
.offset {
IntOffset(mOffsetInt, 0)
}
.size(14.dp)
.background(BaseColor.bluePrimary, RoundedCornerShape(50))
.drawWithContent {
drawContent()
drawCircle(
Color.White,
size.minDimension / 4.0f
)
}
.pointerInput(mOffsetX) {
detectHorizontalDragGestures(
onDragEnd = {
// LogUtil.i("Drag#onDragEnd")
onDragEnd(mOffsetInt / mWidth.toFloat())
},
onHorizontalDrag = { change: PointerInputChange, dragAmount: Float ->
// LogUtil.i("Drag#onHorizontalDrag: change:${change} dragAmount:${dragAmount}")
LogUtil.i("Slider# before dragAmount:$dragAmount mOffsetX:$mOffsetX")
mOffsetX += dragAmount
var offerInt = mOffsetX.roundToInt()
offerInt = if (offerInt > 0) offerInt else 0
offerInt = if (offerInt < mWidth) offerInt else mWidth
mOffsetInt = offerInt
LogUtil.i("Slider# dragAmount:$dragAmount mOffsetX:$mOffsetX offerInt:$offerInt")
}
)
}
)
}
}