Last active
March 17, 2024 01:22
-
-
Save fvilarino/449e7255c705748a429b08a285ca1ae3 to your computer and use it in GitHub Desktop.
Chip Selector - Chip with Border
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Composable | |
fun Chip( | |
label: String, | |
isSelected: Boolean, | |
onClick: () -> Unit, | |
modifier: Modifier = Modifier | |
) { | |
// 1 | |
val borderColor = MaterialTheme.colorScheme.onSurface | |
val backgroundColor = if (isSelected) { | |
MaterialTheme.colorScheme.primaryContainer | |
} else { | |
MaterialTheme.colorScheme.secondaryContainer | |
} | |
val textColor = if (isSelected) { | |
MaterialTheme.colorScheme.onPrimaryContainer | |
} else { | |
MaterialTheme.colorScheme.onSecondaryContainer | |
} | |
// 2 | |
val path = remember { Path() } | |
// 3 | |
val borderWidth = with(LocalDensity.current) { 2.dp.toPx() } | |
Box( | |
modifier = modifier | |
// 4 | |
.drawWithCache { | |
// 5 | |
val cornerRadius = size.height / 2f | |
// 6 | |
path.moveTo(borderWidth + size.width / 2f, borderWidth) | |
path.lineTo(size.width - borderWidth - cornerRadius, borderWidth) | |
path.quadraticBezierTo( | |
size.width - borderWidth, | |
borderWidth, | |
size.width - borderWidth, | |
borderWidth + cornerRadius | |
) | |
path.quadraticBezierTo( | |
size.width - borderWidth, | |
size.height - borderWidth, | |
size.width - borderWidth - cornerRadius, | |
size.height - borderWidth | |
) | |
path.lineTo(borderWidth + cornerRadius, size.height - borderWidth) | |
path.quadraticBezierTo( | |
borderWidth, | |
size.height - borderWidth, | |
borderWidth, | |
size.height - cornerRadius - borderWidth | |
) | |
path.quadraticBezierTo( | |
borderWidth, | |
borderWidth, | |
borderWidth + cornerRadius, | |
borderWidth | |
) | |
path.close() | |
// 7 | |
onDrawBehind { | |
// 8 | |
drawPath( | |
path = path, | |
color = backgroundColor, | |
style = Fill, | |
) | |
// 9 | |
if (isSelected) { | |
drawPath( | |
path = path, | |
color = borderColor, | |
style = Stroke(width = borderWidth), | |
) | |
} | |
} | |
} | |
.clickable(onClick = onClick) | |
) { | |
Text( | |
text = label, | |
color = textColor, | |
fontWeight = FontWeight.Bold, | |
modifier = Modifier | |
.padding(horizontal = 24.dp, vertical = 16.dp) | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment