<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hugo Djemaa on Medium]]></title>
        <description><![CDATA[Stories by Hugo Djemaa on Medium]]></description>
        <link>https://medium.com/@realsoc?source=rss-4c50fb4315ca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RgquSesciuyXEx3H</url>
            <title>Stories by Hugo Djemaa on Medium</title>
            <link>https://medium.com/@realsoc?source=rss-4c50fb4315ca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 13:10:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@realsoc/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Drawing with Compose : The Animated String Path]]></title>
            <link>https://realsoc.medium.com/drawing-with-compose-the-animated-string-path-2dfa14af0739?source=rss-4c50fb4315ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/2dfa14af0739</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[drawing-tutorial]]></category>
            <dc:creator><![CDATA[Hugo Djemaa]]></dc:creator>
            <pubDate>Thu, 30 Nov 2023 05:46:57 GMT</pubDate>
            <atom:updated>2023-12-02T20:03:04.833Z</atom:updated>
            <content:encoded><![CDATA[<h3>Drawing with Compose : The Animated String Path</h3><p>Probability of headache : 😌</p><blockquote>M140 20C73 20 20 74 20 140c0 135 136 170 228 303 88–132 229–173 229–303 0–66–54–120–120–120–48 0–90 28–109 69–19–41–60–69–108–69z</blockquote><p>Are these encrypted instructions meant to lead to some treasure? The first few decimals of pi? Or is it simply a code that must be entered into a bunker located on a desert island in the Pacific Ocean every 108 minutes, otherwise the world will end?</p><p>Nothing of the sort, this is an SVG path. The string describes the drawing of a shape :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35UEq8fAdywxIQtlwJR81g.png" /><figcaption>To understand the drawing better, nothing better than … a drawing [<a href="https://svg-path-visualizer.netlify.app/#M140%2020C73%2020%2020%2074%2020%20140c0%20135%20136%20170%20228%20303%2088-132%20229-173%20229-303%200-66-54-120-120-120-48%200-90%2028-109%2069-19-41-60-69-108-69z">SVG Path Visualizer</a>]</figcaption></figure><ul><li><strong>M140 20</strong> means <em>Pick up the pen and Move it to { x: 140, y: 20 }</em></li><li><strong>C73 20 20 74 20 140</strong> means <em>Put down the pen and Draw a Bézier curve from the current point to a new point { x: 20, y: 140 }. The start control point is { x: 73, y: 20 } and the end control point is { x: 20, y: 74 }</em></li><li>…</li></ul><p>If … is not enough for you, get a look at this <a href="https://svg-path-visualizer.netlify.app/#M140%2020C73%2020%2020%2074%2020%20140c0%20135%20136%20170%20228%20303%2088-132%20229-173%20229-303%200-66-54-120-120-120-48%200-90%2028-109%2069-19-41-60-69-108-69z">SVG Path Visualizer</a>.</p><p>Now you know what a path is. You can find some by opening an SVG file with a word processing software.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;!-- Will you find the path ??? --&gt;<br>&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; width=&quot;33&quot; height=&quot;31&quot; viewBox=&quot;0 0 33 31&quot; fill=&quot;none&quot;&gt;<br>  &lt;g id=&quot;github-mark-white 1&quot; clip-path=&quot;url(#clip0_252_1107)&quot;&gt;<br>    &lt;path id=&quot;Vector&quot; fill-rule=&quot;evenodd&quot; clip-rule=&quot;evenodd&quot; d=&quot;M16.2648 0C7.4436 0 0.3125 7.10417 0.3125 15.893C0.3125 22.9184 4.88164 28.8652 11.2203 30.97C12.0127 31.1282 12.303 30.628 12.303 30.2072C12.303 29.8388 12.2769 28.5759 12.2769 27.26C7.83936 28.2074 6.91528 25.3654 6.91528 25.3654C6.20213 23.5235 5.14548 23.0501 5.14548 23.0501C3.69307 22.0765 5.25128 22.0765 5.25128 22.0765C6.86238 22.1818 7.70777 23.7079 7.70777 23.7079C9.13373 26.1285 11.4315 25.4445 12.3559 25.0235C12.4878 23.9972 12.9107 23.2868 13.3597 22.8922C9.82042 22.5238 6.09666 21.1556 6.09666 15.0508C6.09666 13.3142 6.73013 11.8933 7.73389 10.7883C7.57552 10.3937 7.02075 8.76202 7.89258 6.57814C7.89258 6.57814 9.23952 6.15705 12.2766 8.20951C13.5769 7.86162 14.9178 7.68465 16.2648 7.68316C17.6118 7.68316 18.9848 7.86754 20.2527 8.20951C23.2901 6.15705 24.6371 6.57814 24.6371 6.57814C25.5089 8.76202 24.9538 10.3937 24.7954 10.7883C25.8256 11.8933 26.433 13.3142 26.433 15.0508C26.433 21.1556 22.7092 22.4973 19.1435 22.8922C19.7247 23.3921 20.2263 24.3392 20.2263 25.8391C20.2263 27.9704 20.2002 29.6809 20.2002 30.2069C20.2002 30.628 20.4908 31.1282 21.283 30.9703C27.6216 28.8649 32.1907 22.9184 32.1907 15.893C32.2168 7.10417 25.0596 0 16.2648 0Z&quot; fill=&quot;#FFFF00&quot;&gt;&lt;/path&gt;<br>  &lt;/g&gt;<br>  &lt;defs&gt;<br>    &lt;clipPath id=&quot;clip0_252_1107&quot;&gt;<br>      &lt;rect width=&quot;32&quot; height=&quot;31&quot; fill=&quot;white&quot; transform=&quot;translate(0.3125)&quot;&gt;&lt;/rect&gt;<br>    &lt;/clipPath&gt;<br>  &lt;/defs&gt;<br>&lt;/svg&gt;</pre><p>Now that you know what a path is, let’s animate one with Compose! And if you ever need a reason to do that, I’ll give you three: it will enhance your knowledge about Compose, you can use it to create a loader, and animations are fuuun!</p><p>I will guide you through building the most important parts of the code. For the complete implementation, you can find a snippet at the end of this article, just above the claps and the comment section 👀.</p><p>First things first, let’s create a preview to test our future composable.</p><p>The composable will take as parameters: a path string, a color, a stroke width, an <a href="https://medium.com/androiddevelopers/easing-in-to-easing-curves-in-jetpack-compose-d72893eeeb4d">easing curve</a> and a duration defining the animation and the now famous modifier.</p><pre>@Preview<br>@Composable<br>fun StringPathAnimation() {<br>    Box(modifier = Modifier.fillMaxSize()) {<br><br>        val path = &quot;M140 20C73 20 20 74 20 140c0 135 136 170 228 303 88-132 229-173&quot; +<br>                &quot; 229-303 0-66-54-120-120-120-48 0-90 28-109 69-19-41-60-69-108-69z&quot;<br><br>        AnimatedPath(<br>            pathStr = path,<br>            color = Color.Red,<br>            strokeWidth = 5.dp,<br>            easing = EaseInOutSine,<br>            duration = 2000,<br>            modifier = Modifier.padding(20.dp)<br>        )<br>    }<br>}</pre><p>In order to work with the path, we need to translate it into something Compose can draw. The DrawScope has a drawPath() function that takes an androidx.compose.ui.graphics.Path—this is a start. Additionally, Compose has a PathParser class that includes the functions:</p><ul><li>parsePathString(pathData: String): PathParser</li><li>toPath(target: Path = Path()): Path</li></ul><p>Nice, right? And it gets even better — it works!</p><pre>with(LocalDensity.current) {<br>  BoxWithConstraints(modifier) {<br><br>    var path by remember { mutableStateOf(Path()) }<br>    val strokeWidthPx = strokeWidth.toPx()<br><br>    LaunchedEffect(pathStr, strokeWidthPx) {<br>      val tmpPath = PathParser().parsePathString(pathStr).toPath()<br>      tmpPath.fillBounds(strokeWidthPx, constraints.maxWidth, constraints.maxHeight)<br>      path = tmpPath<br>  }<br>}</pre><p>The LaunchedEffect will parse the path string into a Path and then scale it to fill the composable.</p><p>Now we have a path, how are we going to draw it progressively ?</p><p>Compose has a class named PathMeasure that will help us do the job.</p><p>After setting a path to PathMeasure, we can obtain the path distance using the length attribute. Additionally, we can retrieve an intermediate path between two distance values with getSegment(). For instance, pathMeasure.getSegment(0f, pathMeasure.length, destination) will place the entire path in the destination, while pathMeasure.getSegment(0f, pathMeasure.length / 2, destination) will place the first half. Can you guess how to get the second half?</p><p>It’s nearly complete now. All that’s left is to integrate PathMeasure into an animation context, and for this, we&#39;ll employ an infinite transition.</p><pre>            val pathMeasure = remember { PathMeasure() }<br><br>            pathMeasure.setPath(path, false)<br><br>            val infiniteTransition = rememberInfiniteTransition(label = &quot;Path infinite transition&quot;)<br><br>            // Animating infinitely a float between 0f and the path length<br>            val progress by infiniteTransition.animateFloat(<br>                initialValue = 0f,<br>                targetValue = pathMeasure.length,<br>                animationSpec = infiniteRepeatable(<br>                    animation = tween(duration, easing = easing),<br>                    repeatMode = RepeatMode.Reverse<br>                ), label = &quot;Path animation&quot;<br>            )<br><br>            // Create a intermediate path from 0f to progress<br>            val animatedPath = remember {<br>                derivedStateOf {<br>                    val destination = Path()<br>                    pathMeasure.setPath(path, false)<br>                    pathMeasure.getSegment(0f, progress, destination)<br>                    destination<br>                }<br>            }<br><br>            // Draw the path<br>            Canvas(modifier = Modifier.fillMaxWidth()) {<br>                drawPath(animatedPath.value, color, style = Stroke(width = strokeWidthPx))<br>            }</pre><p>progress will oscillate between 0f and the path length, guided by the specified easing curve. With each new progress value, the animatedPath will be updated and redrawn on the Canvas. It&#39;s as simple as that!</p><p>Let’s wrap it up :</p><pre>@Composable<br>fun AnimatedPath(<br>    pathStr: String,<br>    color: Color,<br>    strokeWidth: Dp,<br>    easing: Easing,<br>    duration: Int,<br>    modifier: Modifier = Modifier<br>) {<br>    with(LocalDensity.current) {<br>        BoxWithConstraints(modifier) {<br>            var path by remember { mutableStateOf(Path())}<br><br>            val strokeWidthPx = strokeWidth.toPx()<br><br>            // Here we transform the path string in path and make it fill the screen<br>            LaunchedEffect(pathStr, strokeWidthPx) {<br>                val tmpPath = PathParser().parsePathString(pathStr).toPath()<br><br>                tmpPath.fillBounds(strokeWidthPx, constraints.maxWidth, constraints.maxHeight)<br><br>                path = tmpPath<br>            }<br><br><br>            val pathMeasure = remember { PathMeasure() }<br><br>            pathMeasure.setPath(path, false)<br><br>            val infiniteTransition = rememberInfiniteTransition(label = &quot;Path infinite transition&quot;)<br><br>            // Animating infinitely a float between 0f and the path length<br>            val progress by infiniteTransition.animateFloat(<br>                initialValue = 0f,<br>                targetValue = pathMeasure.length,<br>                animationSpec = infiniteRepeatable(<br>                    animation = tween(duration, easing = easing),<br>                    repeatMode = RepeatMode.Reverse<br>                ), label = &quot;Path animation&quot;<br>            )<br><br>            // Create a intermediate path from 0f to progress<br>            val animatedPath = remember {<br>                derivedStateOf {<br>                    val destination = Path()<br>                    pathMeasure.setPath(path, false)<br>                    pathMeasure.getSegment(0f, progress, destination)<br>                    destination<br>                }<br>            }<br><br>            // Draw the path<br>            Canvas(modifier = Modifier.fillMaxWidth()) {<br>                drawPath(animatedPath.value, color, style = Stroke(width = strokeWidthPx))<br>            }<br>        }<br>    }<br>}<br><br>fun Path.fillBounds(strokeWidthPx: Float, maxWidth: Int, maxHeight: Int) {<br>    val pathSize = getBounds()<br>    val matrix = Matrix()<br><br>    val horizontalOffset = pathSize.left - strokeWidthPx / 2<br>    val verticalOffset = pathSize.top - strokeWidthPx / 2<br>    val scaleWidth = maxWidth / (pathSize.width + strokeWidthPx)<br>    val scaleHeight = maxHeight / (pathSize.height + strokeWidthPx)<br>    val scale = min(scaleHeight, scaleWidth)<br><br>    matrix.scale(scale, scale)<br>    matrix.translate(-horizontalOffset, -verticalOffset)<br><br>    transform(matrix)<br>}<br><br>@Preview<br>@Composable<br>fun StringPathAnimation() {<br>    Box(modifier = Modifier.fillMaxSize()) {<br><br>        val path = &quot;M140 20C73 20 20 74 20 140c0 135 136 170 228 303 88-132 229-173&quot; +<br>                &quot; 229-303 0-66-54-120-120-120-48 0-90 28-109 69-19-41-60-69-108-69z&quot;<br><br>        AnimatedPath(<br>            pathStr = path,<br>            color = Color.Red,<br>            strokeWidth = 10.dp,<br>            easing = EaseInOutSine,<br>            duration = 2000,<br>            modifier = Modifier.padding(20.dp)<br>        )<br>    }<br>}</pre><p>And the result ?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FbIBShv0pZIrPEzeoPa%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FbIBShv0pZIrPEzeoPa&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExOWpkY2VtaTNqaXk5eXFvbWRxYWpidGRhMjFwcXR2d3VmbDFsang4dCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FbIBShv0pZIrPEzeoPa%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="413" frameborder="0" scrolling="no"><a href="https://medium.com/media/2170d140473edbd6a91efbb1977cce87/href">https://medium.com/media/2170d140473edbd6a91efbb1977cce87/href</a></iframe><p>I hope you enjoy the reading. Feel free to share the story, give it a clap, and/or leave your comment in the dedicated section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2dfa14af0739" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rewriting the BackStack. A Compose & Navigation story.(Bonus at the end)]]></title>
            <link>https://realsoc.medium.com/rewriting-the-backstack-a-compose-navigation-story-bonus-at-the-end-6e7a1d27eaea?source=rss-4c50fb4315ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e7a1d27eaea</guid>
            <category><![CDATA[jetpack-navigation]]></category>
            <category><![CDATA[navigation-component]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[compose]]></category>
            <dc:creator><![CDATA[Hugo Djemaa]]></dc:creator>
            <pubDate>Thu, 23 Nov 2023 22:05:22 GMT</pubDate>
            <atom:updated>2023-11-23T22:05:22.060Z</atom:updated>
            <content:encoded><![CDATA[<h4>TL;DR : Achieve your ideal back stack by sequentially calling popBackStack() and navigate() on your navigation controller.</h4><p>It all began while I was developing an Android application called CropNGrid, designed to craft grid posts for Instagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*rkdn4kcTTkg7cB3WrS85Zw.jpeg" /><figcaption>This is what a grid post looks like</figcaption></figure><p>I designed the application with three top-level destinations: Home, Info, and Grid List. Clicking on an image in the GridListScreen will lead you to the GridScreen. From the HomeScreen, you can select a picture you want to split and enter the CropperScreen. After completing the cropping process, clicking a button takes you to the GridScreen, which displays the grid resulting from the split and crop. The GridScreen is a direct child of the GridListScreen destination, so ideally, navigating back should land you in the GridListScreen.</p><p>…</p><p>😮‍💨🤯</p><p>A picture is worth a thousand words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UV2XlqyYXB2iZtppG0nR0A.png" /><figcaption>Maybe this one just worth a 500 words 😅</figcaption></figure><h4>What is the problem ?</h4><p>The issue here lies in the navigation flow. If you simply use the <em>navigate()</em> method from the CropperScreen to the GridScreen, pressing the back arrow or performing the back gesture will take the user back to the CropperScreen. If you send an email and you press back, you don’t want to come back to writing an email, right ?</p><p>💡</p><p>For this, there is a (well documented) solution : the NavOptions’ <em>popUpTo()</em>.</p><pre>fun NavController.navigateToGrid(gridId: String) {<br>    this.navigate(&quot;grid/$gridId&quot;) { // this: NavOptionsBuilder<br>        popUpTo(homeNavigationRoute) // Will clear the backstack and let only HomeScreen in it<br>        launchSingleTop = true<br>    }<br>}</pre><p>Great! Now, what happens if I press the back button while on the GridScreen? I’m taken back to the Home. However, remember that I intended for a back action from the GridScreen to take me to the GridListScreen, its direct ancestor in the natural navigation flow.</p><p>Any ideas?</p><p>This question is not rhetorical; I extensively searched for online article about <em>how to modify the back stack</em> without success. I tried different methods (from okay-ish to very ugly), but finally, I found a solution that I’m somewhat happy with, and I wanted to share it with you. If you have an alternative approach, please share it in the comments!</p><pre>NavHost(<br>  navController = navController,<br>  ...<br>) { // this : NavGraphBuilder<br>  ...<br>  cropperScreen(<br>    onCropComplete = {<br>      navController.popBackStack(homeNavigationRoute, false)<br>      navController.navigateToGridList()<br>      navController.navigateToGrid(it)<br>                     },<br>  )</pre><p>When the user completes the crop/split of the image in the CropperScreen, the app will invoke <em>onCropComplete()</em>. This function will sequentially: clear the back stack, navigate to the GridListScreen, and then navigate to the GridScreen.</p><p>Voilà!</p><p>The user smoothly arrives at the GridScreen with a neat back stack: GridListScreen on top and HomeScreen right after. All of this happens seamlessly without any blinking or lagging.</p><p>🥳🥳🥳</p><h4>Bonus part :</h4><p>If you are using transitions in the navigation component, you likely have a lot of boilerplate code. I created a class aimed at making NavHost transitions more readable.</p><p>Here’s how I set up the NavHost component:</p><pre>    val transitions = Transitions.BASE<br>        .addTransition(<br>            homeNavigationRoute,<br>            gridListNavigationRoute,<br>            rightToLeftTransition(EaseOutCubic, 500)<br>        ).addTransition(<br>            gridListNavigationRoute,<br>            homeNavigationRoute,<br>            leftToRightTransition(EaseOutCubic, 500)<br>        ).addTransition(<br>            gridListNavigationRoute,<br>            infoNavigationRoute,<br>            leftToRightTransition(EaseOutCubic, 500)<br>        ).addTransition(<br>            infoNavigationRoute,<br>            gridListNavigationRoute,<br>            rightToLeftTransition(EaseOutCubic, 500)<br>        ).addTransition(<br>            homeNavigationRoute,<br>            infoNavigationRoute,<br>            rightToLeftTransition(EaseOutCubic, 500)<br>        ).addTransition(<br>            infoNavigationRoute,<br>            homeNavigationRoute,<br>            leftToRightTransition(EaseOutCubic, 500)<br>        )<br><br><br>    NavHost(<br>        navController = navController,<br>        startDestination = startDestination,<br>        enterTransition = transitions.enterTransitionChain,<br>        exitTransition = transitions.exitTransitionChain,<br>        popEnterTransition = transitions.popEnterTransitionChain,<br>        popExitTransition = transitions.popExitTransitionChain,<br>        modifier = modifier<br>    )</pre><p>If you’re interested in the implementation details, you can check out the <a href="https://github.com/realsoc/CropNGrid/blob/main/app/src/main/kotlin/com/realsoc/cropngrid/navigation/Transitions.kt"><em>Transitions</em> class</a> in the CropNGrid repository. The app is open source!</p><p>Don’t forget to clap if you enjoyed the article, and feel free to leave comments for suggestions and feedback!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e7a1d27eaea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Drawing with Compose : The Zebra Spacer]]></title>
            <link>https://realsoc.medium.com/drawing-with-compose-the-zebra-spacer-a9b0d804cf02?source=rss-4c50fb4315ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9b0d804cf02</guid>
            <category><![CDATA[ui-design]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Hugo Djemaa]]></dc:creator>
            <pubDate>Mon, 20 Nov 2023 23:11:57 GMT</pubDate>
            <atom:updated>2023-11-30T03:47:47.584Z</atom:updated>
            <content:encoded><![CDATA[<h3>Drawing with Compose : The Zebra Spacer</h3><p>Compose is a powerful toolkit: it alleviates the headache caused by the back and forth between (hopefully) the Kotlin logic and the XML views. It aids in decoupling UI logic from the Android framework, thereby enhancing the testability and maintainability of the app. <strong>And</strong> it speeds-up a lot the UI development.</p><p>Thanks to 👏 at the end of this article if you learn something. And do not hesitate to comment or keep in touch for any comment/suggestion.</p><p>Today, I will use Compose to implement a component I found on <a href="https://randoma11y.com/">https://randoma11y.com/</a> : The Zebra Spacer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PsqixMK319P_fZZe5SD_QQ.png" /><figcaption>The Zebra Spacer, simple and effective 👌</figcaption></figure><p><strong>TL;DR : </strong>Jump to the end of the article</p><p>Randoma11y is a tool designed to identify strong-contrasted color combinations, particularly useful when striving to create an accessible product.</p><p>Let’s start creating an environment to help us develop the spacer.</p><p>I suppose you already have worked (at least played) with Compose and know how to set it up.</p><p>Otherwise you can check the <a href="https://developer.android.com/jetpack/compose/setup">Compose Quick Start</a> on Android Developer.</p><p>The minimum to make this code work is to add this in your app build.gradle.</p><pre>android {<br>    buildFeatures {<br>        compose = true<br>    }<br><br>    composeOptions {<br>        kotlinCompilerExtensionVersion = &quot;1.5.4&quot;<br>    }<br>}<br>dependencies {<br>    val composeBom = platform(&quot;androidx.compose:compose-bom:2023.10.01&quot;)<br>    implementation(composeBom)<br>    implementation(&quot;androidx.compose.ui:ui&quot;) // You won&#39;t need this if you decide to use Material* <br>    implementation(&quot;androidx.compose.ui:ui-tooling-preview&quot;)<br>    debugImplementation(&quot;androidx.compose.ui:ui-tooling&quot;)<br>}<br></pre><p>First the spacer, we know it will accept a <strong>Color</strong> and a <strong>Modifier</strong> (<a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier">modifier should always be the first optional parameter</a>).</p><pre>@Composable<br>fun TheZebraSpacer(<br>    color: Color,<br>    modifier: Modifier = Modifier<br>) {<br>    // For now we put a border to visualise the spacer in the preview<br>    Spacer(modifier = modifier.border(width = 1.dp, color = color))<br>}</pre><p>Then we create two previews : a vertical and an horizontal spacer.</p><pre>// A strong-contrasted color combination<br>private val backgroundColor = Color(0xFF593072)<br>private val primaryColor = Color(0xFFFFFF00)<br><br>@Preview<br>@Composable<br>fun TheVerticalZebraSpacerPreview() {<br>    Column(modifier = Modifier<br>        .fillMaxWidth()<br>        .background(backgroundColor)<br>        .padding(16.dp)<br>    ) {<br>        Text(<br>            stringResource(R.string.lorem_1),<br>            color = primaryColor)<br>        TheZebraSpacer(<br>            color = primaryColor,<br>            modifier = Modifier<br>                .height(100.dp)<br>                .padding(10.dp)<br>                .fillMaxWidth()<br>        )<br>        Text(<br>            stringResource(R.string.lorem_2),<br>            color = primaryColor<br>        )<br>    }<br>}<br><br>@Preview<br>@Composable<br>fun TheHorizontalZebraSpacerPreview() {<br>    Row(modifier = Modifier<br>        .background(backgroundColor)<br>        .height(IntrinsicSize.Max)<br>    ) {<br>        Icon(<br>            imageVector = Icons.Default.Face,<br>            contentDescription = &quot;Face icon&quot;,<br>            modifier = Modifier.size(100.dp),<br>            tint = primaryColor<br>        )<br>        TheZebraSpacer(<br>            color = primaryColor,<br>            modifier = Modifier<br>                .width(100.dp)<br>                .padding(10.dp)<br>                .fillMaxHeight()<br>        )<br>        Icon(<br>            imageVector = Icons.Default.Home,<br>            contentDescription = &quot;Home icon&quot;,<br>            modifier = Modifier.size(100.dp),<br>            tint = primaryColor<br>        )<br>    }<br>}</pre><p>You should now see this on Android Studio preview (you might have to build the preview a first time, then it updates and renders by itself).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*qV84KxaYHXzqHDgXfj4Usg.png" /></figure><p>Perfect ! We are all set-up and we can start to implement the Zebra Spacer. We won’t have to modify the preview anymore.</p><p>How are we going to tackle the problem ? For one question there are an infinity of answers, thousands of valid ones, and hundreds of good ones. <br>We could — for example — draw each line from where it should starts to where it should ends, but it will ask us to calculate the exact position of each point. I love to do maths, but what I like more is being pragmatic. Here is how we are going to do.</p><p>First, we will draw vertical lines all over the spacer zone, then we are going to rotate everything by 45 degrees, finally we will clip the drawing to fit in the spacer bounds.</p><p>We are going to use the <strong>drawWithContent</strong> modifier, which helps to draw things before or after a composable content (in our case it doesn’t matter as the spacer has no contents). This modifier accepts a lambda scoped on <strong>ContentDrawScope </strong>which have a size, a center and tons of helpful functions to draw. We are also going to use the CompositionLocal LocalDensity because <strong>drawWithContent</strong> use pixels but we want to use Dp to adapt to screens size.</p><p>Note : We also could have used Canvas(modifier: Modifier) { /* draw here */ } which is a wrapper around the <strong>drawBehind()</strong> modifier.</p><pre>@Composable<br>fun TheZebraSpacer(<br>    color: Color,<br>    modifier: Modifier = Modifier<br>) {<br>    with(LocalDensity.current) {<br>        Spacer(modifier = modifier<br>            .border(width = 1.dp, color = color) // We keep the border for now to help us visualise the spacer boundaries<br>            .drawWithContent {<br>              // This is were the magic happens<br>            }<br>        )<br>    }<br>}</pre><h4>Drawing vertical lines</h4><p>We can start adding two optional parameters which are the space between two lines and line width. From that we calculate the gap between the left side of a line and the left side of the following one, in order to have the total line count. <br>We calculate also the line length. As our spacer is a rectangle, the maximum size a line can have is the hypothenuse (which is the square root of the sum of its squared sides 🤓). As we are going to clip everything : no need to overthink, we use the max size to draw every line.<br>We are going to center everything around the drawing zone center (which luckily lives in the ContentDrawScope).</p><p>Ready ?? Boom !</p><pre>@Composable<br>fun TheZebraSpacer(<br>    color: Color,<br>    modifier: Modifier = Modifier,<br>    lineSpace: Dp = 10.dp,<br>    strokeWidth: Dp = 3.dp<br>) {<br>    with(LocalDensity.current) {<br>        val gapBetweenLines = (lineSpace + strokeWidth).toPx()<br>        Spacer(modifier = modifier<br>            .border(width = 1.dp, color = color)<br>            .drawWithContent {<br>                val lineCount = (size.width / gapBetweenLines).toInt()<br>                val lineLength = sqrt(size.height.pow(2) + size.width.pow(2))<br>                val startY = center.y - lineLength / 2f<br>                val endY = center.y + lineLength / 2f<br>                (0..lineCount)<br>                  .map { it * gapBetweenLines }<br>                  .map { x -&gt;<br>                  // We are creating an array containing all the positions along the x-axis<br>                    // Then each position we draw a line :<br>                    drawLine(<br>                        color = color,<br>                        start = Offset(x, startY),<br>                        end = Offset(x, endY),<br>                        strokeWidth = strokeWidth.toPx()<br>                    )<br>                }<br>            }<br>        )<br>    }<br>}</pre><p>Pretty simple right ?? Now let’s look at the preview :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*SDsgzWzDC_-7PcMb2Qjj1g.png" /></figure><p>Now will you believe me if I tell you the hard part is behind ?</p><p><strong>No ???</strong></p><p>Ok, let’s rotate.</p><h4>Rotating</h4><pre>@Composable<br>fun TheZebraSpacer(<br>    color: Color,<br>    modifier: Modifier = Modifier,<br>    lineSpace: Dp = 10.dp,<br>    strokeWidth: Dp = 3.dp<br>) {<br>    with(LocalDensity.current) {<br>        val gapBetweenLines = (lineSpace + strokeWidth).toPx()<br>        Spacer(modifier = modifier<br>            .border(width = 1.dp, color = color)<br>            .drawWithContent {<br>                val lineCount = (size.width / gapBetweenLines).toInt()<br>                val lineLength = sqrt(size.height.pow(2) + size.width.pow(2))<br>                val startY = center.y - lineLength / 2f<br>                val endY = center.y + lineLength / 2f<br>                rotate(45f, center) {<br>                  (0..lineCount)<br>                    .map { it * gapBetweenLines }<br>                    .map { x -&gt;<br>                        drawLine(<br>                            color = color,<br>                            start = Offset(x, startY),<br>                            end = Offset(x, endY),<br>                            strokeWidth = strokeWidth.toPx()<br>                        )<br>                    }<br>                }<br>            }<br>        )<br>    }<br>}</pre><p>Looking for the diff? Let me help you, we just added <em>rotate(45f, center) {…}.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*wMzNbKc9OpLbD_TLy_FhWw.png" /></figure><p>And a part of it is not even mandatory, we could just have written <em>rotate(45f) {…}. </em>But I’d rather add the second parameter in this article because it is <strong>very important</strong> to keep in mind a rotation is always around a point : the <strong>pivot</strong>. The rotate function has its default to center, that’s why it is not necessary to rewrite it. But if you change it to Offset(0f, 0f) you will see the difference.</p><p>Let’s add one line before and one line after in order to cover the whole spacer area, the second preview seems a little bit short.</p><pre>@Composable<br>fun TheZebraSpacer(<br>    color: Color,<br>    modifier: Modifier = Modifier,<br>    lineSpace: Dp = 10.dp,<br>    strokeWidth: Dp = 3.dp<br>) {<br>    with(LocalDensity.current) {<br>        val gapBetweenLines = (lineSpace + strokeWidth).toPx()<br>        Spacer(modifier = modifier<br>            .border(width = 1.dp, color = color)<br>            .drawWithContent {<br>                val lineCount = ceil(size.width / gapBetweenLines).toInt()<br>                val lineLength = sqrt(size.height.pow(2) + size.width.pow(2))<br>                val startY = center.y - lineLength / 2f<br>                val endY = center.y + lineLength / 2f<br>                rotate(45f, center) {<br>                    (-1..lineCount)<br>                        .map { it * gapBetweenLines }<br>                        .map { x -&gt;<br>                            drawLine(<br>                                color = color,<br>                                start = Offset(x, startY),<br>                                end = Offset(x, endY),<br>                                strokeWidth = strokeWidth.toPx()<br>                            )<br>                        }<br>                }<br>            }<br>        )<br>    }<br>}</pre><p>The only difference is the call to <em>ceil() </em>in the lineCount definition and the IntRange starting at -1 instead of 0. (Ceil will round up instead of down)</p><p>Last but not least, let’s clip everything to the spacer area.</p><p><strong>Clipping</strong></p><pre>@Composable<br>fun TheZebraSpacer(<br>    color: Color,<br>    modifier: Modifier = Modifier,<br>    lineSpace: Dp = 10.dp,<br>    strokeWidth: Dp = 3.dp<br>) {<br>    with(LocalDensity.current) {<br>        val gapBetweenLines = (lineSpace + strokeWidth).toPx()<br>        Spacer(modifier = modifier<br>            .border(width = 1.dp, color = color)<br>            .drawWithContent {<br>                val lineCount = ceil(size.width / gapBetweenLines).toInt()<br>                val lineLength = sqrt(size.height.pow(2) + size.width.pow(2))<br>                val startY = center.y - lineLength / 2f<br>                val endY = center.y + lineLength / 2f<br>                clipRect(<br>                    left = 0f,<br>                    top = 0f,<br>                    right = size.width,<br>                    bottom = size.height<br>                ) {<br>                    rotate(45f, center) {<br>                        (-1..lineCount)<br>                            .map { it * gapBetweenLines }<br>                            .map { x -&gt;<br>                                drawLine(<br>                                    color = color,<br>                                    start = Offset(x, startY),<br>                                    end = Offset(x, endY),<br>                                    strokeWidth = strokeWidth.toPx()<br>                                )<br>                            }<br>                    }<br>                }<br>            }<br>        )<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*eW3boEEY72rPDWUhK7NoBQ.png" /></figure><p>Finally we remove the border modifier and…</p><h4>The result</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*28Sz6_503DUVnsV-pEiMWQ.png" /><figcaption>Tadaaa, The<strong> Zebra Spacer </strong>!!</figcaption></figure><p>You can find the snippet with the final code <a href="https://gist.github.com/realsoc/d8d01d16b08f6929077440766f918e5e">here</a> ! It wasn’t that hard right ?</p><p>Don’t forget to clap if you liked this article, or if you like zebras, or even the weird choice of color. And do no hesitate to comment or keep in touch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9b0d804cf02" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>