'How to draw ticket shape in Jetpack Compose
Solution 1:[1]
class TicketShape(private val cornerRadius: Float) : Shape {
override fun createOutline(
size: Size,
layoutDirection: LayoutDirection,
density: Density
): Outline {
return Outline.Generic(
// Draw your custom path here
path = drawTicketPath(size = size, cornerRadius = cornerRadius)
)
}
}
fun drawTicketPath(size: Size, cornerRadius: Float): Path {
return Path().apply {
reset()
// Top left arc
arcTo(
rect = Rect(
left = -cornerRadius,
top = -cornerRadius,
right = cornerRadius,
bottom = cornerRadius
),
startAngleDegrees = 90.0f,
sweepAngleDegrees = -90.0f,
forceMoveTo = false
)
lineTo(x = size.width - cornerRadius, y = 0f)
// Top right arc
arcTo(
rect = Rect(
left = size.width - cornerRadius,
top = -cornerRadius,
right = size.width + cornerRadius,
bottom = cornerRadius
),
startAngleDegrees = 180.0f,
sweepAngleDegrees = -90.0f,
forceMoveTo = false
)
lineTo(x = size.width, y = size.height - cornerRadius)
// Bottom right arc
arcTo(
rect = Rect(
left = size.width - cornerRadius,
top = size.height - cornerRadius,
right = size.width + cornerRadius,
bottom = size.height + cornerRadius
),
startAngleDegrees = 270.0f,
sweepAngleDegrees = -90.0f,
forceMoveTo = false
)
lineTo(x = cornerRadius, y = size.height)
// Bottom left arc
arcTo(
rect = Rect(
left = -cornerRadius,
top = size.height - cornerRadius,
right = cornerRadius,
bottom = size.height + cornerRadius
),
startAngleDegrees = 0.0f,
sweepAngleDegrees = -90.0f,
forceMoveTo = false
)
lineTo(x = 0f, y = cornerRadius)
close()
}
}
Now use it with any Composable,
MyComp(
Modifier.clip(
TicketShape( 24.dp.toPx() )
)
)
Source: https://juliensalvi.medium.com/custom-shape-with-jetpack-compose-1cb48a991d42
We're basically inheriting from a Shape object, which is something the clip modifiers and other shape parameters accept to render the desired shape. Other examples are RectangleShape, CircleShape, RoundedCornerShape, etc, which are pre-built for compose. You need a distinct shape and so, you require to create your own Shape object. You didn't exactly need to create the class separately if you don't wish to use it again and again. In that case, an object at the place of usage should have sufficed, but it appears that it is not just a decoration so you might wanna create the class itself to not have to create the same objects at multiple places.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

