Custom Shapes in Jetpack Compose: Heart
This file contains 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 heart(): GenericShape { | |
return GenericShape { size, _ -> | |
heartPath(size = size) | |
} | |
} |
This file contains 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
class Heart: Shape { | |
override fun createOutline( | |
size: Size, | |
layoutDirection: LayoutDirection, | |
density: Density | |
): Outline { | |
val path = Path().apply { | |
heartPath(size = size) | |
close() | |
} | |
return Outline.Generic(path) | |
} | |
} |
This file contains 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
fun Path.heartPath(size: Size): Path { | |
//the logic is taken from StackOverFlow [answer](https://stackoverflow.com/a/41251829/5348665)and converted into extension function | |
val width: Float = size.width | |
val height: Float = size.height | |
// Starting point | |
moveTo(width / 2, height / 5) | |
// Upper left path | |
cubicTo( | |
5 * width / 14, 0f, | |
0f, height / 15, | |
width / 28, 2 * height / 5 | |
) | |
// Lower left path | |
cubicTo( | |
width / 14, 2 * height / 3, | |
3 * width / 7, 5 * height / 6, | |
width / 2, height | |
) | |
// Lower right path | |
cubicTo( | |
4 * width / 7, 5 * height / 6, | |
13 * width / 14, 2 * height / 3, | |
27 * width / 28, 2 * height / 5 | |
) | |
// Upper right path | |
cubicTo( | |
width, height / 15, | |
9 * width / 14, 0f, | |
width / 2, height / 5 | |
) | |
return this | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment