Skip to content

Instantly share code, notes, and snippets.

@bagus2x
Created October 11, 2022 03:46
Show Gist options
  • Save bagus2x/6506b2a29ce7a503278f97ba4e25477d to your computer and use it in GitHub Desktop.
Save bagus2x/6506b2a29ce7a503278f97ba4e25477d to your computer and use it in GitHub Desktop.
Rating Bar Jetpack Compose with onClick Handler
@Composable
fun RatingBar(
rating: Float,
onChange: (Int, Float) -> Unit,
max: Int
) {
Row {
val value = rating * max
val fullStar = value.toInt()
var fractionStar = value - fullStar
repeat(max) { index ->
val fraction = if (index < fullStar) 1F else {
val fraction = fractionStar
fractionStar = 0F
fraction
}
Star(
fraction = fraction,
onClick = { onChange(index, (index + 1F) / max) }
)
}
}
}
@Composable
fun Star(
modifier: Modifier = Modifier,
fraction: Float,
color: Color = Color.Yellow,
onClick: () -> Unit,
size: Dp = 24.dp
) {
Box(
modifier = modifier
.size(size)
.clip(StarShape)
.clickable(onClick = onClick)
.border(width = 1.dp, shape = StarShape, color = color)
.drawBehind {
val width = this.size.width
val height = this.size.height
drawRect(
color = color,
size = Size(
width = fraction * width,
height = height
)
)
}
)
}
private val StarShape = GenericShape { size, _ ->
moveTo(12.0f / 24 * size.width, 17.27f / 24 * size.height)
lineTo(18.18f / 24 * size.width, 21.0f / 24 * size.height)
relativeLineTo(-1.64f / 24 * size.width, -7.03f / 24 * size.height)
lineTo(22.0f / 24 * size.width, 9.24f / 24 * size.height)
relativeLineTo(-7.19f / 24 * size.width, -0.61f / 24 * size.height)
lineTo(12.0f / 24 * size.width, 2.0f / 24 * size.height)
lineTo(9.19f / 24 * size.width, 8.63f / 24 * size.height)
lineTo(2.0f / 24 * size.width, 9.24f / 24 * size.height)
relativeLineTo(5.46f / 24 * size.width, 4.73f / 24 * size.height)
lineTo(5.82f / 24 * size.width, 21.0f / 24 * size.height)
close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment