Skip to content

Instantly share code, notes, and snippets.

@micHar
Last active May 25, 2021 08:27
Show Gist options
  • Save micHar/3926308e9467bac806f15f615b8a9c72 to your computer and use it in GitHub Desktop.
Save micHar/3926308e9467bac806f15f615b8a9c72 to your computer and use it in GitHub Desktop.
private data class Border(val strokeWidth: Dp, val cornerRadius: Dp, val color: Color)
fun Modifier.bookCardBackground(
itemIndex: Int,
allItemsSize: Int
): Modifier {
val border = Border(
strokeWidth = 1.dp,
cornerRadius = 16.dp,
color = Color.Green
)
return when {
allItemsSize <= 1 -> this.then(theOnlyItemStroke(border))
itemIndex == 0 -> this.then(firstItemStroke(border))
itemIndex == allItemsSize - 1 -> this.then(lastItemStroke(border))
else -> this.then(middleItemStroke(border))
}.fillMaxSize()
}
private fun Modifier.theOnlyItemStroke(border: Border): Modifier = this.then(
border(
width = border.strokeWidth,
color = border.color,
shape = RoundedCornerShape(border.cornerRadius)
).clip(RoundedCornerShape(border.cornerRadius))
)
private fun Modifier.firstItemStroke(border: Border): Modifier = this
.then(
itemStroke(border) { brush, stroke, cornerRadius ->
drawRoundRect(
brush = brush,
topLeft = Offset(
stroke.width / 2,
stroke.width / 2
),
size = Size(
size.width - stroke.width,
size.height - stroke.width / 2 + cornerRadius.y // clip the stroke from bottom
),
style = stroke,
cornerRadius = cornerRadius
)
}
)
.clip(RoundedCornerShape(topStart = border.cornerRadius, topEnd = border.cornerRadius))
private fun Modifier.lastItemStroke(border: Border): Modifier = this
.then(
itemStroke(border) { brush, stroke, cornerRadius ->
drawRoundRect(
brush = brush,
topLeft = Offset(
stroke.width / 2,
stroke.width / 2 - cornerRadius.y //clip the stroke from top
),
size = Size(
size.width - stroke.width,
size.height - stroke.width / 2 + cornerRadius.y //adjust stroke length at the bottom
),
style = stroke,
cornerRadius = cornerRadius
)
}
)
.clip(RoundedCornerShape(bottomStart = border.cornerRadius, bottomEnd = border.cornerRadius))
private fun Modifier.middleItemStroke(border: Border): Modifier = this.then(
itemStroke(border){ brush, stroke, _ ->
drawRect(
brush = brush,
topLeft = Offset(
stroke.width / 2,
-stroke.width //clip the stroke from top
),
size = Size(
size.width - stroke.width,
size.height + stroke.width * 2 //clip the stroke from bottom
),
style = stroke
)
}
)
private fun Modifier.itemStroke(
border: Border,
drawBorder: DrawScope.(Brush, Stroke, CornerRadius) -> Unit
): Modifier = this.then(
Modifier.drawWithCache {
val brush = SolidColor(border.color)
val stroke = Stroke(border.strokeWidth.toPx())
val cornerRadius = CornerRadius(border.cornerRadius.toPx(), border.cornerRadius.toPx())
onDrawWithContent {
drawContent()
clipRect { drawBorder(brush, stroke, cornerRadius) }
}
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment