Last active
March 5, 2022 16:50
-
-
Save thelumiereguy/19ee82b8b91a628c7ce010c8a174c670 to your computer and use it in GitHub Desktop.
A Jetpack Compose based example to draw a modified Cantor Circle using recursion
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
const val MAX_ITERATIONS = 7f | |
@OptIn(ExperimentalGraphicsApi::class) | |
@Composable | |
fun CantorCirclePatternComposable(modifier: Modifier) { | |
BoxWithConstraints(modifier = Modifier) { | |
val frame by rememberInfiniteTransition().animateFloat( | |
initialValue = 1f, | |
targetValue = 3f, | |
animationSpec = infiniteRepeatable( | |
tween( | |
10000, | |
easing = FastOutSlowInEasing | |
), | |
RepeatMode.Reverse | |
), | |
) | |
val halfWidth = remember { | |
constraints.maxWidth / 2 | |
} | |
val halfHeight = remember { | |
constraints.maxHeight / 2 | |
} | |
fun DrawScope.drawCircle( | |
center: Offset, | |
radius: Float, | |
iteration: Int = 1, | |
) { | |
if (iteration > MAX_ITERATIONS) { | |
return | |
} | |
val color = iteration / MAX_ITERATIONS | |
rotate( | |
degrees = (iteration % 2) * 180f * frame, | |
pivot = center | |
) { | |
// draw original circle | |
drawCircle( | |
color = Color( | |
abs(color - 0.1f), | |
color, | |
abs(color - 0.01f), | |
), | |
radius = radius, | |
center = center, | |
blendMode = BlendMode.Xor | |
) | |
val halfRadius = radius / 2f | |
// draw circle inside to the left | |
drawCircle( | |
center - Offset(halfRadius * frame, 0f), | |
radius = halfRadius, | |
iteration + 1 | |
) | |
// draw circle inside to the top | |
drawCircle( | |
center - Offset(0f, halfRadius * frame), | |
radius = halfRadius, | |
iteration + 1 | |
) | |
// draw circle inside to the right | |
drawCircle( | |
center + Offset(halfRadius * frame, 0f), | |
radius = halfRadius, | |
iteration + 1 | |
) | |
// draw circle inside to the bottom | |
drawCircle( | |
center + Offset(0f, halfRadius * frame), | |
radius = halfRadius, | |
iteration + 1 | |
) | |
} | |
} | |
Canvas(modifier = modifier.background(Color.Black)) { | |
// Move origin to center | |
translate( | |
left = halfWidth.toFloat(), | |
top = halfHeight.toFloat() | |
) { | |
drawCircle( | |
center = Offset(0f, 0f), | |
radius = minOf(halfWidth, halfHeight).toFloat(), | |
) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment