Skip to content

Instantly share code, notes, and snippets.

@realsoc
Created November 20, 2023 21:20
Show Gist options
  • Save realsoc/d8d01d16b08f6929077440766f918e5e to your computer and use it in GitHub Desktop.
Save realsoc/d8d01d16b08f6929077440766f918e5e to your computer and use it in GitHub Desktop.
Implementation of a Zebra Spacer on Android using Kotlin + Compose
private val backgroundColor = Color(0xFF593072)
private val primaryColor = Color(0xFFFFFF00)
@Composable
fun TheZebraSpacer(
color: Color,
modifier: Modifier = Modifier,
lineSpace: Dp = 10.dp,
strokeWidth: Dp = 3.dp
) {
with(LocalDensity.current) {
val gapBetweenLines = (lineSpace + strokeWidth).toPx()
Spacer(modifier = modifier
//.border(width = 1.dp, color = color)
.drawWithContent {
val lineCount = ceil(size.width / gapBetweenLines).toInt()
val lineLength = sqrt(size.height.pow(2) + size.width.pow(2))
val startY = center.y - lineLength / 2f
val endY = center.y + lineLength / 2f
clipRect(
left = 0f,
top = 0f,
right = size.width,
bottom = size.height
) {
rotate(45f, center) {
(-1..lineCount)
.map { it * gapBetweenLines }
.map { x ->
drawLine(
color = color,
start = Offset(x, startY),
end = Offset(x, endY),
strokeWidth = strokeWidth.toPx()
)
}
}
}
}
)
}
}
@Preview
@Composable
fun TheVerticalZebraSpacerPreview() {
Column(
modifier = Modifier
.fillMaxWidth()
.background(backgroundColor)
.padding(16.dp)
) {
Text(
stringResource(R.string.lorem_1),
color = primaryColor
)
TheZebraSpacer(
color = primaryColor,
modifier = Modifier
.height(100.dp)
.padding(10.dp)
.fillMaxWidth()
)
Text(
stringResource(R.string.lorem_2),
color = primaryColor
)
}
}
@Preview
@Composable
fun TheHorizontalZebraSpacerPreview() {
Row(
modifier = Modifier
.background(backgroundColor)
.height(IntrinsicSize.Max)
) {
Icon(
imageVector = Icons.Default.Face,
contentDescription = "Face icon",
modifier = Modifier.size(100.dp),
tint = primaryColor
)
TheZebraSpacer(
color = primaryColor,
modifier = Modifier
.width(100.dp)
.padding(10.dp)
.fillMaxHeight()
)
Icon(
imageVector = Icons.Default.Home,
contentDescription = "Home icon",
modifier = Modifier.size(100.dp),
tint = primaryColor
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment