<?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 Yuriy Skul on Medium]]></title>
        <description><![CDATA[Stories by Yuriy Skul on Medium]]></description>
        <link>https://medium.com/@yuriyskul?source=rss-eaf677d34c58------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*M10bjgITcuxDGRJBOSmOrw.jpeg</url>
            <title>Stories by Yuriy Skul on Medium</title>
            <link>https://medium.com/@yuriyskul?source=rss-eaf677d34c58------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 01:00:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yuriyskul/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[Jetpack Compose: Animated Snake Border for Rectangle Shapes]]></title>
            <link>https://proandroiddev.com/jetpack-compose-animated-snake-border-for-rectangle-shapes-31de5e9ef713?source=rss-eaf677d34c58------2</link>
            <guid isPermaLink="false">https://medium.com/p/31de5e9ef713</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Yuriy Skul]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 15:49:11 GMT</pubDate>
            <atom:updated>2026-03-30T15:49:11.231Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oIvo_V7tlkVq9mewnkfjVA.jpeg" /><figcaption>Glowing running snake border</figcaption></figure><h4>Introduction</h4><p>A glowing snake border may sound like a simple UI effect. On the web, there are many examples, variants, and breakdowns of how to build it. But on native Android, I have not really seen solid implementations done properly. Most of them are either simplified to a circle with plain rotation, or they use the same rotation-based progress idea even for rectangle shapes. As a result, the motion stops being uniform and starts to feel uneven and broken.</p><p>Let’s fix that properly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*WYtX9eUXEuCIxTyr7noqxw.gif" /><figcaption>Rectangle snake Snake border Burtton</figcaption></figure><p><strong>Warning</strong>: this solution is primarily a showcase or a learning exercise. <strong>Never ever ship a continuously running animation like this in production unless you fully understand its performance implications and can guarantee it stays within the 16 ms frame budget.</strong></p><p>You will pay for this twice: first in development and maintenance — including the cost of supporting older and lower-end devices — and then, more importantly, in user experience. Users are extremely sensitive to even minor stutters, freezes, or small FPS drops, especially on budget devices where performance is already constrained.</p><h4>This article is part of a glowing snake border series:</h4><ul><li>Part 1 —<a href="https://medium.com/@yuriyskul/making-an-animated-glowing-circular-button-with-blur-and-gradient-shadows-in-jetpack-compose-72ffe9a3169d"> Animated Snake Border for </a><a href="https://medium.com/@yuriyskul/making-an-animated-glowing-circular-button-with-blur-and-gradient-shadows-in-jetpack-compose-72ffe9a3169d">CircleShape</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*YZ2Mlfl6h-kPAPVN0h3rwQ.gif" /><figcaption>Simple rotation solution from Part 1</figcaption></figure><ul><li>Part 2 — Animated Snake Border for Rectangle Shapes . — <em>You are here</em></li><li>Part 3 — Animated Snake Border for any Shape; Path &amp; Sampling trick (coming soon).</li></ul><p><strong>Current article full code: </strong><a href="https://github.com/yuriyskulskiy/android-compose-playground/tree/main/app/src/main/java/com/skul/yuriy/composeplayground/feature/animatedRectButton">link</a> with <a href="https://github.com/yuriyskulskiy/android-compose-playground/tree/main/app/src/main/java/com/skul/yuriy/composeplayground/feature/animatedRectButton/snake">running snake</a>.</p><h4>Problem</h4><p>A common approach is to animate movement by rotating a line and taking its intersection with the path as the current position.<br>This works perfectly for circles, but for shapes where width and height differ significantly, the speed varies along the path.<br>Also, joins between vertical and horizontal segments often create visible seams, breaking the illusion of a continuous shape.<br>Rounded corners are often ignored completely, with no support for inner (inset) or outer (outset) borders that extend beyond the composable bounds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*g0kWNzGQAWY04-ghzuzFyA.gif" /><figcaption>My 2020y Java/View solution — no corners support</figcaption></figure><h4>Solution Requirements</h4><ul><li>Smooth motion — the velocity vector changes smoothly while its magnitude remains constant</li><li>Two-layer snake body — a blurred halo and a thin stroke core, fading smoothly from head to tail until fully transparent</li><li>No visible seams — the snake must appear continuous across all segment joins</li><li>Support for circular shapes</li><li>Support for rectangles with sharp corners</li><li>Rounded corner support</li><li>Support for varying corner radii — the ability to define different radii for each corner</li><li>State persistence — the snake should preserve its state when leaving and re-entering composition</li><li>Encapsulation — the entire effect should be implemented within a single modifier, without spreading logic across the composition</li><li>Dynamic geometry updates — runtime changes in size or shape must not cause discontinuities or jumps; motion should remain smooth and continuous during transitions</li></ul><h4>Implementation</h4><p>This article focuses only on the snake movement.<br>Text-related effects and the glowing halo border when pressed are out of scope and are covered in my previous articles.</p><p><em>Also, for anyone looking for some hidden magic here, there really is none. The whole thing is just a perimeter split into 8 segments: 4 quarter-circle arcs, 2 horizontal lines, and 2 vertical lines. From there, it becomes a fairly boring mechanical routine: compute where the snake head and tail are, determine which segments they fall into, and then render the snake piece by piece inside each affected segment separately.</em></p><p><strong>Step 1 Extract animation STATE:</strong></p><p>By state here I mean the variable that describes the snake movement itself. If we treat the full perimeter as a closed contour of normalized length 1, then that variable is simply the animation progress. It moves from 0 to 1, then jumps back to 0 and repeats. Once this value is known, everything else can be derived from it: the head position, the tail position, and the currently covered perimeter segments.</p><p>This logic could be moved entirely inside the modifier with Modifier.composed, but I also needed the same progress value outside the modifier to keep it synchronized with the drop shadow angle inside GlowingText. That is why I moved it into a separate helper, rememberRectSnakeState.</p><p>Lifecycle observation is also encapsulated there, so the state is not animated when it does not need to be. Another common mistake is to tie progress directly to frame ticks. In that case, if FPS drops by X times,<br> the snake speed also drops by X times. Here the progress is time-based, so its speed does not depend on frame rate.</p><pre> @Stable<br>  class RectSnakeState internal constructor(<br>      initialProgress: Float = 0f<br>  ) {<br>      var progress by mutableFloatStateOf(initialProgress)<br>          internal set<br><br>      internal var isEnabled by mutableStateOf(true)<br>      internal var isLifecycleRunning by mutableStateOf(true)<br><br>      val isRunning: Boolean<br>          get() = isEnabled &amp;&amp; isLifecycleRunning<br><br>      companion object {<br>          // state saver<br>          ...<br>      }<br>  }</pre><pre> @Composable<br>  fun rememberRectSnakeState(<br>      enabled: Boolean = true<br>  ): RectSnakeState {<br>      val state = rememberSaveable(saver = RectSnakeState.Saver) {<br>          RectSnakeState()<br>      }<br>      val lifecycleOwner = LocalLifecycleOwner.current<br><br>      state.isEnabled = enabled<br><br>      DisposableEffect(lifecycleOwner) {<br>          // lifecycle observation<br>          ...<br>      }<br><br>      LaunchedEffect(state.isRunning) {<br>          if (!state.isRunning) return@LaunchedEffect<br><br>          val startProgress = state.progress<br>          val startFrameNanos = withFrameNanos { it }<br><br>          while (true) {<br>              val frameNanos = withFrameNanos { it }<br>              val elapsedMs = (frameNanos - startFrameNanos) / 1_000_000f<br>              val loopProgress = elapsedMs / SnakeLoopAnimationDurationMs<br>              state.progress = normalizeSnakeProgress(startProgress + loopProgress)<br>          }<br>      }<br><br>      return state<br>  }</pre><p><strong>Step 2: Build the perimeter geometry</strong></p><p>The first thing we need is an explicit perimeter model, because the snake should move not along an abstract shape, but along a fully defined geometric track.</p><p>In this solution, the perimeter geometry is a precomputed description of that track built from the current size, shape, stroke placement, and resolved corner radii.</p><p>As part of that, the full border is reduced to 8 ordered segments: 4 straight edges and 4 quarter-circle arcs. For each segment, we compute its geometry, its length, and the offset at which it starts along the full perimeter.</p><p>The final geometry object contains the track bounds (left, top, right, bottom), the radius of each corner (topLeftRadius, topRightRadius, bottomRightRadius, bottomLeftRadius), the centers of the four corner arcs (topRightCenter, bottomRightCenter, bottomLeftCenter, topLeftCenter), the length of every segment, the accumulated start offset of every segment, and the total perimeter length.</p><p>Based on this geometry, at any moment of the animation we can determine which segments the snake currently spans and the exact positions of its head and tail on the border.</p><p>— quarterTurn is the length coefficient for a quarter-circle arc.<br> — topLen, rightLen, bottomLen, and leftLen are the lengths of the straight perimeter segments.<br> — topRightArcLen, bottomRightArcLen, bottomLeftArcLen, and topLeftArcLen are the lengths of the four corner arcs.<br> — segmentLengths stores the real length of each of the 8 perimeter segments.<br> — segmentStarts stores the accumulated offset at which each segment begins along the full perimeter. (Pixel points)<br> — totalLen is the total length of the entire perimeter track.<br> — topRightCenter, bottomRightCenter, bottomLeftCenter, and topLeftCenter are the arc centers used later for rendering and point lookup.</p><pre> private fun buildRectSnakeTrackGeometry(...): RectSnakeTrackGeometry? {<br>      // track bounds, resolved corner radii, and validation<br>      ...<br><br>      val quarterTurn = PI.toFloat() / 2f<br><br>      val topLen = (trackWidth - radii.topLeft - radii.topRight).coerceAtLeast(0f)<br>      val rightLen = (trackHeight - radii.topRight - radii.bottomRight).coerceAtLeast(0f)<br>      val bottomLen = (trackWidth - radii.bottomRight - radii.bottomLeft).coerceAtLeast(0f)<br>      val leftLen = (trackHeight - radii.bottomLeft - radii.topLeft).coerceAtLeast(0f)<br><br>      val topRightArcLen = (quarterTurn * radii.topRight).coerceAtLeast(0f)<br>      val bottomRightArcLen = (quarterTurn * radii.bottomRight).coerceAtLeast(0f)<br>      val bottomLeftArcLen = (quarterTurn * radii.bottomLeft).coerceAtLeast(0f)<br>      val topLeftArcLen = (quarterTurn * radii.topLeft).coerceAtLeast(0f)<br><br>      val segmentLengths = floatArrayOf(<br>          topLen,<br>          topRightArcLen,<br>          rightLen,<br>          bottomRightArcLen,<br>          bottomLen,<br>          bottomLeftArcLen,<br>          leftLen,<br>          topLeftArcLen<br>      )<br><br>      val segmentStarts = FloatArray(segmentLengths.size)<br>      var totalLen = 0f<br>      for (index in segmentLengths.indices) {<br>          segmentStarts[index] = totalLen<br>          totalLen += segmentLengths[index]<br>      }<br><br>      return RectSnakeTrackGeometry(<br>          left = left,<br>          top = top,<br>          right = right,<br>          bottom = bottom,<br>          topLeftRadius = radii.topLeft,<br>          topRightRadius = radii.topRight,<br>          bottomRightRadius = radii.bottomRight,<br>          bottomLeftRadius = radii.bottomLeft,<br>          segmentLengths = segmentLengths,<br>          segmentStarts = segmentStarts,<br>          totalLen = totalLen,<br>          // arc centers<br>          topRightCenter = Offset(...),<br>          bottomRightCenter = Offset(...),<br>          bottomLeftCenter = Offset(...),<br>          topLeftCenter = Offset(...),<br>          // rendering-related geometry fields<br>          ...<br>      )<br>  }</pre><p><strong>Step 3: Convert animation progress into snake head and tail positions</strong></p><p>At this step, we stop working with the static perimeter model and derive the current snake span from the animation progress. This is an internal derived state used only for rendering, not the animation state object<br> from Step 1. The progress value is first converted into headDistance, which represents the current position of the snake head along the full perimeter length. The actual snake length is then computed from<br> snakeLengthFraction * totalLen, and tailDistanceis obtained by moving backward from the head along the same perimeter. Once both positions are known, they define the full visible snake span that will later be<br> rendered from tail to head across the affected segments.</p><p>— progress is the normalized animation progress.<br> — wrappedProgress keeps the progress inside the looping 0..1 range (normalized animation progress).<br> — headDistance is the current head position measured along the full perimeter.<br> — snakeLengthFraction defines how much of the perimeter the snake should occupy.<br> — snakeLength is the real snake length on the current track.<br> — tailDistance is the tail position measured backward from the head.<br> — alphaAtDistance(distance) gives the fade value for any point inside the current snake span.</p><pre> private fun buildRectSnakeProgressState(<br>      progress: Float,<br>      snakeLengthFraction: Float,<br>      totalLen: Float<br>  ): RectSnakeProgressState {<br>      // Keep progress inside the stable [0, 1) loop even if the input overflows.<br>      val wrappedProgress = ((progress % 1f) + 1f) % 1f<br>      val headDistance = wrappedProgress * totalLen<br>      val snakeLength = (snakeLengthFraction.coerceIn(0f, 1f) * totalLen)<br>          .coerceIn(0f, totalLen)<br>      val tailDistance = headDistance - snakeLength<br><br>      fun alphaAtDistance(distance: Float): Float {<br>          val relative = (distance - tailDistance) / snakeLength<br>          return relative.coerceIn(0f, 1f)<br>      }<br><br>      return RectSnakeProgressState(<br>          headDistance = headDistance,<br>          snakeLength = snakeLength,<br>          tailDistance = tailDistance,<br>          alphaAtDistance = ::alphaAtDistance //(Float) -&gt; Float<br>      )<br>  }</pre><p><strong>Step 4: Split the snake span across the affected segments<br></strong> If the snake is short enough, it may fit entirely inside a single segment.<br>In other cases, it spans multiple segments at once.<br>For each affected segment, we determine which part should be drawn. <br>This gives us the exact intervals that will be rendered on straight edges and corner arcs.</p><p>— startDistance and endDistance define the current snake span on the perimeter: startDistance is the current tail position, and endDistance is the current head position, both measured along the full perimeter path.<br> — wrapped keeps the current distance inside the 0..totalLen perimeter range, so we can correctly determine which segment it belongs to.<br> — findSegmentIndex(...) tells us which segment the current part of the snake belongs to.<br> — segmentStart and segmentEnd define the boundaries of that segment.<br> — intervalEnd gives the end of the current piece that can be drawn inside this segment before moving to the next one.</p><pre>private fun drawDistanceIntervalNative(<br>      canvas: android.graphics.Canvas,<br>      geometry: RectSnakeTrackGeometry,<br>      startDistance: Float,<br>      endDistance: Float,<br>      colorFrom: Color,<br>      colorTo: Color,<br>      alphaAtDistance: (Float) -&gt; Float,<br>      paint: Paint,<br>  ) {<br>      val totalLen = geometry.totalLen<br>      var current = startDistance<br><br>      while (current &lt; endDistance) {<br>          val wrapped = ((current % totalLen) + totalLen) % totalLen<br>          val segmentIndex = findSegmentIndex(geometry.segmentStarts, geometry.segmentLengths, wrapped)<br>          val segmentStart = geometry.segmentStarts[segmentIndex]<br>          val segmentEnd = segmentStart + geometry.segmentLengths[segmentIndex]<br>          val intervalEnd = min(endDistance, current + (segmentEnd - wrapped))<br><br>          drawSegmentPartNative(<br>              canvas = canvas,<br>              geometry = geometry,<br>              segmentIndex = segmentIndex,<br>              startDistance = wrapped,<br>              endDistance = wrapped + (intervalEnd - current),<br>              colorFrom = colorFrom,<br>              colorTo = colorTo,<br>              alphaAtDistance = alphaAtDistance,<br>              paint = paint<br>          )<br><br>          current = intervalEnd<br>      }<br>  }</pre><p><strong>Step 5. Render the snake inside drawWithCache</strong></p><p>At this point, the geometry and the snake intervals are already known, so only rendering remains. I do it inside drawWithCache to prepare geometry and paint objects once and reuse them during drawing. This keeps the<br>whole effect inside a single modifier.</p><p>From there, the logic is simple: draw every segment currently covered by the snake. Depending on the current head and tail positions, that may be one segment or several at once. With a large snake fraction such as<br> 0.75f, the snake can span most of the perimeter and sometimes touch all 8 segments. Each affected segment is rendered only for the interval that belongs to the current snake span.</p><p>Straight segments and corner arcs are rendered differently, but both follow the same interval logic. Segment joints have to use cut ends rather than round caps. If a rounded head or tail is needed, it should be<br>drawn separately as a circle or semicircle.</p><pre>fun Modifier.rectSnakeBorder(<br>      state: RectSnakeState,<br>      ...<br>  ): Modifier = this.drawWithCache {<br>      val geometry = buildRectSnakeTrackGeometry(...)<br>      if (geometry == null) {<br>          return@drawWithCache onDrawBehind {}<br>      }<br><br>      val snakeState = buildRectSnakeProgressState(<br>          progress = state.progress,<br>          snakeLengthFraction = snakeLengthFraction,<br>          totalLen = geometry.totalLen<br>      )<br><br>      val bodyStrokePaint = createBodyStrokePaint(...)<br>      val glowStrokePaint = createGlowStrokePaint(...)<br>      val glowHeadPaint = createGlowHeadPaint(...)<br><br>      val head = pointAtDistance(geometry, snakeState.headDistance)<br><br>      onDrawBehind {<br>          if (snakeState.snakeLength &gt; 0f) {<br>              drawIntoCanvas { canvas -&gt;<br>                  val nativeCanvas = canvas.nativeCanvas<br><br>                  // Draw the large glowing outer snake body.<br>                  drawSnakeLayerNative(<br>                      canvas = nativeCanvas,<br>                      geometry = geometry,<br>                      snakeState = snakeState,<br>                      colorFrom = glowColorFrom,<br>                      colorTo = glowColorTo,<br>                      paint = glowStrokePaint<br>                  )<br><br>                  // Draw the glowing outer snake head.<br>                  nativeCanvas.drawCircle(<br>                      head.x,<br>                      head.y,<br>                      glowingStrokeWidthPx / 2f,<br>                      glowHeadPaint<br>                  )<br><br>                  // Draw the thin inner snake body on top of the glow.<br>                  drawSnakeLayerNative(<br>                      canvas = nativeCanvas,<br>                      geometry = geometry,<br>                      snakeState = snakeState,<br>                      colorFrom = bodyColorFrom,<br>                      colorTo = bodyColorTo,<br>                      paint = bodyStrokePaint<br>                  )<br>              }<br><br>              // Draw the sharp inner head point.<br>              drawCircle(<br>                  color = bodyColorTo,<br>                  radius = bodyStrokeWidthPx / 2f,<br>                  center = head<br>              )<br>          }<br>      }<br>  }</pre><p>The nativeCanvas is needed here for the outer halo body and the halo head, because BlurMaskFilter is only available through the native Android paint pipeline. The inner snake body is not blurred, but it is still<br> rendered through the same native path simply to reuse the same drawSnakeLayerNative(...) logic.</p><h4>Blur mask seams problem</h4><p>There are still some small visual seams between blurred line segments and blurred arcs, especially when the halo body width becomes large. This current approach does not fully eliminate them. I will cover that separately in the next article using a sampling-based approach.</p><h4>Conclusion</h4><p>This solution supports CircleShape, RectangleShape, and RoundedCornerShape with varying corner radii, which in practice covers most regular UI elements. For any other generic Shape, I fail explicitly with: error(“rectSnakeBorder supports only RoundedCornerShape, RectangleShape, and CircleShape”)</p><p>But for custom shapes, is there a more universal solution that works for any closed shape?</p><p>Check out my next article for a more universal solution.</p><p><strong>Github link</strong>: <a href="https://github.com/yuriyskulskiy/android-compose-playground/tree/main/app/src/main/java/com/skul/yuriy/composeplayground/feature/animatedRectButton">whole article code</a> and <a href="https://github.com/yuriyskulskiy/android-compose-playground/tree/main/app/src/main/java/com/skul/yuriy/composeplayground/feature/animatedRectButton/snake">only animated snake package</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31de5e9ef713" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/jetpack-compose-animated-snake-border-for-rectangle-shapes-31de5e9ef713">Jetpack Compose: Animated Snake Border for Rectangle Shapes</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack Compose Metaball Edge Effect — Final Part]]></title>
            <link>https://proandroiddev.com/jetpack-compose-metaball-edge-effect-final-part-ac8a4cc7a425?source=rss-eaf677d34c58------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac8a4cc7a425</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[animation]]></category>
            <dc:creator><![CDATA[Yuriy Skul]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 15:27:31 GMT</pubDate>
            <atom:updated>2026-03-21T16:13:07.195Z</atom:updated>
            <content:encoded><![CDATA[<h3>Jetpack Compose Metaball Edge Effect — Final Part</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oKSE6UFKtEYhxgmqDBv7mw.png" /><figcaption><a href="https://github.com/yuriyskulskiy/android-compose-playground/tree/main/app/src/main/java/com/skul/yuriy/composeplayground/feature/metaballBlur">screen source code</a></figcaption></figure><h4>Background</h4><p>I explored a couple of metaball interaction approaches — nothing too complex, just blur and an alpha threshold.</p><p>But since blur() (API 31+) and RenderEffect (API 31+) have minimum API level requirements, and runtime shaders for alpha filtering (AGSL) are only available from API 33, I also explored alternative approaches for older Android versions.</p><p>I also experimented with implementing the metaball effect between two outlined circular buttons — same approach, but working with strokes instead of filled shapes. AGSL, unlike a color matrix, allows filtering within a specific alpha range, which makes it possible to render (see the bottom Supra section):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*BcYrSQMs8ZhimgPIN791DA.gif" /><figcaption>Metaball across api</figcaption></figure><p><a href="https://github.com/yuriyskulskiy/android-compose-playground/tree/main/app/src/main/java/com/skul/yuriy/composeplayground/feature/gooey">Github link to the metaball across API screen</a></p><p><a href="https://medium.com/@yuriyskul/compose-agsl-shader-gooey-outline-metaball-effect-with-transparent-background-cb8b0e72286c">Medium “Supra” outline article link</a></p><p>But then I had what felt like a simple and elegant idea — to implement the same metaball interaction between scrolling content and the screen edges. In my head, it looked really clean and beautiful, just like object-to-object metaball interaction.</p><p>The POC was very simple — just add vertical gradient bands near the top and bottom edges, blur the circle object, and apply the usual alpha threshold filtering: <a href="https://github.com/yuriyskulskiy/android-compose-playground/tree/main/app/src/main/java/com/skul/yuriy/composeplayground/feature/metaballEdgesAndText/tabs/edge">github link “Gooey Edge” tab</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*_UK9XXKiySTuVavXyjetIA.gif" /><figcaption>POC (metaball edge effect)</figcaption></figure><p>A small exploration of text showed that depending on the blur radius, alpha threshold, and text size, the result can vary — from a large solid blob to a small one, or even nothing at all after alpha filtering.</p><p>A nice property for a text replacement animation is to animate the blur from 0 to a certain value, swap the text, and then animate it back.</p><p>An interesting aspect is that depending on how you tune the metaball parameters, you can get several different behaviors:</p><ul><li>the text transforms into a metaball and then into another text</li><li>the text turns into a metaball, shrinks and disappears, and then the process happens in reverse into a new text</li><li>the text immediately melts and then a new text appears (I don’t like this one)</li></ul><p><a href="https://github.com/yuriyskulskiy/android-compose-playground/tree/main/app/src/main/java/com/skul/yuriy/composeplayground/feature/metaballEdgesAndText/tabs/text">Github link “Text Melt” tab</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*nPWAVvYCNYqdLTg_zRYsnA.gif" /><figcaption>Text morph concept</figcaption></figure><blockquote>Maybe many people (myself included) have done something similar, but the first one who publicly shared it in a clean and well-presented way was <strong>Sinasamaki</strong>, so it’s fair to credit him as someone who brought this idea to Android. All his publications are masterpieces — works of pure art.</blockquote><blockquote><a href="https://www.sinasamaki.com/5-metaball-animations-in-jetpack-compose/"><strong>Sinasamaki — metaball tutorial</strong></a></blockquote><p>The main problem with metaball effects on scrolling text is that blur is applied as a RenderEffect to the entire composable (the scrolling column with text). As a result, the whole text becomes blurred, and the metaball interaction is no longer limited to the desired areas (near the top and bottom edges).</p><p>Instead, the entire content turns into one large dark blob. The stronger and more visually appealing you try to make the metaball effect, the worse it gets — because the text starts interacting with itself first, and only then (with much weaker influence) with the screen edges.</p><p>First, I tried to build a workaround — overlaying top and bottom zones that synchronously render the same text above the original one, blur it, and then apply the same effect, and ended up <a href="https://medium.com/@yuriyskul/text-metaball-scrolling-edges-local-overlay-with-regular-compose-modifier-blur-23b835242815">with a solution that worked, but was still dirty and full of workarounds.</a></p><p>So I came to the conclusion that I needed a <strong>custom blur that could be applied locally to the required areas — the top and bottom edges — with the blur strength increasing as it gets closer to the edges.</strong></p><p>I did a series of tests and experiments around alpha-only blur (since for the metaball effect we don’t need RGB blurring). I compared linear and Gaussian approaches and also experimented with kernel quality — up to around 16dp (~17 taps) was fine, but beyond that it required multiple passes (around 61 taps). Using higher values (100+ taps) quickly becomes too expensive.<br><a href="https://medium.com/@yuriyskul/agsl-alpha-blur-with-local-regions-and-dynamic-radius-linear-and-gaussian-17-61-101-taps-3a36198c9567">My article about custom AGSL local blur with a dynamic radius.</a> <br><a href="https://github.com/yuriyskulskiy/android-compose-playground/tree/main/app/src/main/java/com/skul/yuriy/composeplayground/feature/customAlphaBlur">Github Link to custom Alpha blur experiments</a>.</p><p>For the metaball effect, the following result was chosen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*hSsNmOQP9-tQUwYS9u76JA.gif" /><figcaption>Custom Gaussian AGSL alpha blur</figcaption></figure><p>So I am prepared to do it…</p><h4>Vertical Scrolling Solution</h4><p>The implementation is relatively straightforward. <br>Scrolling text is placed inside a Column with a custom blur modifier applied only to the top and bottom regions. The blur intensity increases progressively as the content approaches the edges of the scrolling container.</p><p>When working with very small elements like text (with stroke widths of just a few dp), all metaball configuration parameters — such as the height of the custom local blur zone or the gradient band — also become extremely small.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*mJhhmhq7DbEkkOtG3ReFgw.png" /><figcaption>Add local blur for MELT effect</figcaption></figure><p>For the Gooey effect, small gradient bands with a height of 16dp were added, with a vertical gradient from 0.4 to 0</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*toHSAwCjRt_hahUyMdEL4w.png" /><figcaption>Add local blur and vertical gradient bands for Gooey effect</figcaption></figure><p>From previous experiments with text and its transformations, two behaviors were observed: the text either disappears or turns into a blob.<br>The disappearance near the edges can be called a “<strong>Melt</strong>” effect, while merging with the edges can also be called “<strong>Gooey</strong>.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*doBo1WfYpy9_f1sikUHrAw.gif" /><figcaption>Result: Text Melt effect</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*CKR3sa0_hxJIPNYTyMf8lg.gif" /><figcaption>Result: Text Gooey Effect</figcaption></figure><p>Solved — but I’m not happy. This is not how I imagined it. It doesn’t look as clean or as impressive as I expected.</p><p>To get at least some decent result, a lot of tuning is required for all these parameters: the blur, the AGSL application area, the alpha threshold, and the maximum alpha in the gradient bands. All of this is also tied to the text size, which, if defined in sp units, is not stable, and even line spacing can introduce a dirty look.</p><p>On top of that, we’re still dependent on API level because of RenderEffect, and no matter how much I tried, a custom alpha blur is not as cheap or as reliable as the system one and can introduce artifacts, especially at the edges.</p><p>Also, the merging of letters with the edge (the desired effect) comes with a downside — letters start merging with each other, and the shapes turn into blobs. Unfortunately, there’s no clean way to get rid of these side effects.</p><p>You can’t prevent a letter from merging with itself, but merging between neighboring letters doesn’t occur in the case of horizontal scrolling.</p><p><a href="https://github.com/yuriyskulskiy/android-compose-playground/tree/main/app/src/main/java/com/skul/yuriy/composeplayground/feature/metaballEdgesAdvanced"><strong>Git hub link: Vertical Scrolling Solution</strong></a></p><h4>Horizontal Scrolling Solution</h4><p>A more stable effect can still be achieved when working with objects that are relatively large compared to the blur radius — for example, large circular elements with icons inside, or just thicker and larger icons. And finally, even a huge single-line text scrolling horizontally tends to look a bit better.</p><pre>//left/right custom blur local zones width and gradient edge boxes width<br>val effectMagnitude = 56.dp <br>val blurRadius = 30.dp<br>val alphaThresholdEffect = alphaThreshold50PercentEffect<br>// Max horizontal gradient<br>val edgeAlpha = 0.5f<br>val circleSize = 72.dp</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*2-gmg2aux2EE91HyxKHj1w.gif" /><figcaption>Horizonal metaball with circle ielements</figcaption></figure><p>In the case of large icons, the effect is still very sensitive to small and thin elements — notice what happens to the Search, Check, and Plus icons. For those, the alpha threshold has to be lowered and the blur radius reduced.</p><pre>val effectMagnitude = 56.dp<br>val blurRadius = 30.dp<br>val alphaThresholdEffect = alphaThreshold50PercentEffect<br>val edgeAlpha = 0.5f<br>val iconSize = 56.dp</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*x650hs9weqrghnkSUbLEnA.gif" /><figcaption>Plain Icons meaball edge effect — very sensitive to small and thin elements</figcaption></figure><pre>val effectMagnitude = 30.dp<br>val blurRadius = 20.dp<br>val alphaThresholdEffect = alphaThreshold30PercentEffect<br>val edgeAlpha = 0.3f<br>//use dp instead of sp for stable effect<br>val HorizontalTextSize = 56.sp </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*WL1n3it2q2fV0EpzJhpq0g.gif" /><figcaption>Metaball Edge Horizontal Text</figcaption></figure><p><strong>Can the custom blur be replaced with a regular one?</strong><br>Yes, but it introduces a key problem: the entire content becomes blurred and starts forming unwanted metaball interactions everywhere. In a previous publication, this exact issue was explored and addressed.</p><p><strong>Can we avoid using RenderEffect blur or a custom blur?<br></strong>Yes, it’s possible. In my previous article, I explored around six different ways to draw a glowing halo border, and the same idea can be applied here — draw a blur mask filter or a halo gradient around a circular element. This way, the inner part will not be deformed.</p><p>However, you still need to solve the problem of neighboring elements intersecting with each other through their “alpha fields,” making the overlapping areas visible. A simple approach is to detect the leftmost and rightmost elements and apply the effect only to them.</p><p><a href="https://github.com/yuriyskulskiy/android-compose-playground/tree/main/app/src/main/java/com/skul/yuriy/composeplayground/feature/metaballEdgeHorizontalScroll"><strong>Github link: Horizontal Scrolling Solution</strong></a></p><h3><strong>Conclusion</strong></h3><p><strong>Yes, a localized custom blur significantly simplifies the problem.</strong><br>However, it does not solve the issue of visual “dirt.” The content still tends to turn into a blob first, and only then begins interacting with the edges.</p><p>The key difference between the metaball effect and something like Liquid Glass ( glassmorphism ) is that <strong>the metaball effect happens between elements</strong>. The effect occurs beyond the UI elements themselves, in the space between them, where many other elements may exist.</p><p>In contrast, glassmorphism is visually <strong>contained within a single component</strong>.<br>Because of that, Liquid Glass usually looks clean and controlled, while metaball effects can quickly become messy when multiple elements are involved.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac8a4cc7a425" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/jetpack-compose-metaball-edge-effect-final-part-ac8a4cc7a425">Jetpack Compose Metaball Edge Effect — Final Part</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Many Ways Do You Know to Draw a Glowing Border in Jetpack Compose?]]></title>
            <link>https://proandroiddev.com/how-many-ways-do-you-know-to-draw-a-glowing-border-in-jetpack-compose-57980d049562?source=rss-eaf677d34c58------2</link>
            <guid isPermaLink="false">https://medium.com/p/57980d049562</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[drawing]]></category>
            <category><![CDATA[graphics]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[animation]]></category>
            <dc:creator><![CDATA[Yuriy Skul]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 15:25:13 GMT</pubDate>
            <atom:updated>2026-03-15T15:25:13.095Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o7aTveOgCBmpfblktoAlHw.png" /><figcaption>AI-generated feature image created with ChatGPT. GPT said it doesn’t need a credit line.</figcaption></figure><p><em>If I asked you how many ways you know to draw a glowing rounded-rectangle border in Jetpack Compose, what would your answer be? One? Two? Maybe three? I started with the same assumption, then ended up exploring a whole sequence of approaches to solve what first looked like a very small drawing task.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*vFByAEA77srr2ZdyHrSNNQ.gif" /><figcaption>Glowing Borders Showcase</figcaption></figure><h4>Task Definition</h4><ul><li>grow to its full size on press, then shrink back and disappear on release</li><li>support a rectangular shape with rounded corners</li><li>keep the content area transparent, if possible</li><li>be drawn outside the composable bounds the modifier is applied to</li><li>allow stronger glow intensity and alpha than the classic Android shadow</li><li>ideally render both a thin contour stroke and an outer glowing halo in one modifier, in a single effect pass</li></ul><h4>0. PNG border</h4><p><em>API support: All API levels</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*LfYP9M03JwJPi-_20UJO7Q.gif" /><figcaption>PNG Crossfade Halo HWUI</figcaption></figure><p>I would not use this as the main solution, but it is still a valid proof of concept.</p><p>The idea is simple: prepare two PNG/WebP images, one for the idle state and one for the active state, then switch between them on press, wrapped in the Crossfade composable. <br>So if you use this approach, ask your designer to make the center transparent from the start. Otherwise, you will have to clear the middle area in code, like I did in this example</p><p>Apply a small scale and a negative offset to the Image modifier to make the border extend outside the composable bounds.</p><p>This approach should not be underestimated, because it moves part of the complexity to the designer side and gives developers more time to focus on business tasks.</p><h4><strong>1. Multi-Layer Halo</strong></h4><p><em>API support: All API levels</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*v7eO-yiY1Akxbv1gN2wUQw.gif" /><figcaption>Multi-Layer Halo HWUI Demo</figcaption></figure><p>The core idea is simple: instead of using real blur, the glow is faked by drawing the same rounded rectangle many times, expanding it layer by layer and fading each outer stroke.</p><p>Getting outside the composable bounds is also straightforward here. Since drawBehind operates in the drawing phase rather than the layout phase, it can paint beyond the composable’s measured size. In practice,<br> that means moving the shape’s topLeft into negative coordinates and drawing it larger than the original box.</p><pre>this.drawBehind {<br>    val layers = 25<br> <br>    repeat(layers) { index -&gt;<br>     ...<br><br>        drawRoundRect(<br>        ...<br>        )<br>    }</pre><p>In practice, I would not consider this a strong production option. It works more as a proof of concept that this kind of glow can be approximated without blur or shaders.</p><p>To get a really smooth visual result, the number of layers has to grow roughly with the border thickness. In other words, the thicker the halo gets, the more stacked strokes you need to keep the gradient from<br> looking stepped. That quickly makes the approach expensive and visually inefficient.</p><p>So the only case where it can reasonably compete with other techniques at the same performance budget is a very thin border, where only a small number of layers is needed. Once the glow becomes wider, the method<br> stops scaling well both visually and technically.</p><h4>2. BlurMaskFilter: A Classic Android Glow</h4><p>BlurMaskFilter <em>has been part of Android since API 1. But once Android moved to hardware-accelerated rendering starting from API 11, mask filters were no longer part of the most reliable path. So on older devices, expect surprises.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*I5n5OM_t6ytj5cR2rvlY7Q.gif" /><figcaption>BlurMaskFilter Halo HWUI Demo</figcaption></figure><p>This time the glow is no longer faked with many strokes. Instead, the border is drawn once as a real outline, and the softness comes from BlurMaskFilter applied to the native paint.</p><pre>val shadowPaint = Paint().apply {<br>    asFrameworkPaint().apply {<br>        ...<br>        maskFilter = BlurMaskFilter(blurRadiusPx, BlurMaskFilter.Blur.NORMAL)<br>    }<br>}<br><br>onDrawWithContent {<br>    drawContent()<br>    clipPath(path, ClipOp.Difference) {<br>        drawIntoCanvas { canvas -&gt;<br>            canvas.drawPath(path, shadowPaint)<br>        }<br>    }<br>}</pre><p>In this approach, the border extends beyond the composable mainly because it is drawn as a stroke pass. A stroked outline is centered on the path itself, so part of its width naturally falls outside the original<br> contour. After that, BlurMaskFilter spreads those pixels even further outward, turning the stroke into a soft halo.</p><p>This is probably the most familiar approach for this kind of glow effect on Android.</p><h4>3. RenderEffect Blur</h4><p><em>This approach requires Android 12 (API 31) or higher.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*6DthXo-lksPZbRS7YGgMHA.gif" /><figcaption>Blur RenderEffect Halo HWUI Demo</figcaption></figure><p>The solution here is to draw the glow in a separate layer and then scale that layer with graphicsLayer.scaleX and graphicsLayer.scaleY. Blur is applied through RenderEffect, which is conceptually the same kind of mechanism the blur() modifier relies on under the hood. As a result, the halo visually grows outside the composable.</p><pre>val blurEffect = RenderEffect.createBlurEffect(…).asComposeRenderEffect()<br>...<br>Modifier.graphicsLayer {<br>  scaleX = …<br>  scaleY = …<br>  renderEffect = blurEffect<br>}</pre><p>The main limitation of this approach is that the blur cannot be confined strictly to the outer border area. Once RenderEffect is applied, it affects the entire layer output, so producing a clean outside-only glow with transparent inner cutout is not possible in the same pass.</p><p>There is also a second issue: if the content is placed in that same layer, it becomes affected by the effect as well. To avoid that, the implementation uses two stacked Box layers. The first one draws the blurred glow, while the second one sits above it as a regular box with any solid background and the content.</p><p>The thin border is drawn separately. It is placed before the graphicsLayer, so it does not get blurred or scaled together with the glow. Because of that, it stays clear and preserves the shape of the rectangle.</p><p>In practice, I would not use this approach. Blur is a much better fit for whole-layer effects than for a local border around a specific shape. Here it can be made to work, but only with extra layering and structural compromises.</p><h4>4. ShadowLayer: The Old Shadow API as a Border Effect</h4><p><em>API support: Android API 1+, but practical behavior depends more on the rendering pipeline than on API availability alone but on older devices, expect surprises.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*UBnERJKWFaQnDnh2F4VatQ.gif" /><figcaption>ShadowLayer Halo HWUI Demo</figcaption></figure><p>The trick here is to let Paint.setShadowLayer() do most of the work. Instead of building the glow manually, the outline is drawn as a path, and the shadow layer turns it into a soft halo around the shape.</p><p>The problem is that opacity control here is limited. This API was designed for shadows, and shadows in Android are not really meant to look highly saturated. Because of that, the result remains quite transparent<br> and does not feel like a strong glow.</p><p>The workaround here is to draw the same path multiple times. A single shadow pass looks too transparent, so repeated passes are used to build up a denser glow.</p><pre> onDrawWithContent {<br>      clipPath(path, ClipOp.Difference) {<br>          drawIntoCanvas { canvas -&gt;<br>              repeat(passes) {<br>                  canvas.drawPath(path, shadowPaint)<br>              }<br>          }<br>      }<br>      drawContent()<br>  }</pre><p>In other words, the visual density does not come from one strong shadow, but from several repeated shadow passes stacked on top of each other.</p><p>Drawing outside the composable here comes from the API out of the box.</p><p>One clear advantage is that this approach works with a Path, so it is not limited to rectangular shapes. In principle, it can be used with any custom shape that can be drawn as a path. Another nice detail is that it naturally leaves a thin visible line near the edge of the composable, which helps preserve the outline of the shape</p><p>In practice, I would not use this approach. It feels like a workaround, because it relies on drawing the same path multiple times just to build up enough visible glow.</p><h4>5. Gradient Brushes: Building a Glow from Parts</h4><p><em>API support: All API levels</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*UAa7hTuP69Y3QXjbOnMhdQ.gif" /><figcaption>Gradient Halo HWUI Demo</figcaption></figure><p>This approach constructs the border from separate gradient pieces. The straight edges are drawn with linear gradients, while the rounded corners are drawn with radial gradients, then mirrored around the rectangle to assemble the full halo.</p><p>The downside is that drawWithCache does not really save us here. The brushes still depend on the current halo width, and the corner gradient also depends on the shape ratio, so both have to be recalculated during animation. A more performance-oriented alternative would be to always draw the halo at its maximum width and animate only its alpha from 0 to 1. The animation would look quite similar, but the rendering would be cheaper.</p><p>But this solution uses a true halo-width animation. The optimization is that only one radial brush is created for the corners and reused four times through transforms, while one linear brush is used for all side gradients.</p><p>The thin stroke is also handled with a small optimization: it remains bright while the halo is still expanded, not only while the finger is down. This avoids extra redraw work during tap spam.</p><p>Going outside the composable is fully manual. The gradients are drawn beyond the original bounds, then reused for the other sides and corners through translate, scale, and rotate.</p><p>Despite its complexity, I would still consider this approach for real use. Its behavior is predictable, and it remains a practical option for older devices as well.</p><h4>6. AGSL border</h4><p><em>Android 13+, API 33</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*8Ck3iFq60iQ2ICp_nhFSQg.gif" /><figcaption>AGSL Halo HWUI Demo</figcaption></figure><p>This way is different from the previous ones. Here the border is no longer built from many drawing passes, blur tricks, or gradient parts. Instead, the whole effect is described directly inside one AGSL hader. That includes both parts of the border:</p><ul><li>the thin contour near the shape edge</li><li>the outer halo that fades away with distance</li></ul><p>So instead of combining several drawing techniques, we describe the full border in one shader and let it decide how strong the glow should be at every pixel.</p><p>In this implementation, the same AGSL shader is used in two different ways.</p><p><strong>6.1 AGSL via RenderEffect</strong></p><p>In the first version, the shader is attached through RenderEffect. This makes it behave more like a post-processing effect applied to the composable layer.</p><p><strong>6.2 AGSL via Canvas Paint</strong></p><p>In the second version, the same shader is attached directly to a native Paint object and drawn through canvas.</p><p>So the visual logic stays the same, but the execution path changes. Instead of passing through RenderEffect, the shader is used like a normal paint shader during canvas drawing.</p><p>The important point is that these are not two different border designs. It is the same border, the same shader, and the same visual model. The only difference is how that shader is executed.</p><p>In both AGSL versions, transparency comes from the shader itself: it generates alpha only outside the rounded rectangle. The difference is in composition. In the RenderEffect path, the shader reads the source<br> layer and blends the halo behind it. In the Canvas Paint path, the shader draws the halo on a transparent base first, and the content is drawn on top afterward.</p><p>So yes, AGSL handles this task very well. But for a simple glowing border like this, I would not personally use it. I would rather keep AGSL for something more crazy and visually outstanding, which is exactly what the next chapter is about.</p><h4>7. Fire Shader: Turning the Border into a Crazy Ice-Fire Effect</h4><p><em>Android 13+, API 33</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*WFCt-p7Zd5vBZfiCWtJbmA.gif" /><figcaption>Advanced AGSL usage</figcaption></figure><p>This is more of a bonus chapter. It is no longer about the original border requirements, and not really about finding the cleanest implementation of a glowing rounded rectangle. It is simply a demonstration of how far AGSL can be pushed once the border stops being just a border and becomes a full visual effect.</p><p>I first built this shader in <a href="https://www.shadertoy.com/view/fcfGzH">GLSL on ShaderToy</a>. That made the iteration process much faster, because parameters could be changed in real time and the visual result was visible immediately, without rebuilding the<br> Android app after every small tweak. Only after that did I port the effect to AGSL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*86bO5rAZ_0sN_9JB_3BpJg.png" /><figcaption>Path start/end join issue (fixed)</figcaption></figure><p>One of the practical problems was the join on the right side, where the border path wraps from end back to start. The solution was to add a small overlap area where the tail fades out while the head fades in, making the transition much less visible.</p><p><a href="https://github.com/yuriyskulskiy/android-compose-playground/tree/main/app/src/main/java/com/skul/yuriy/composeplayground/feature/animatedBorderRect">Github link</a></p><p>Thanks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57980d049562" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/how-many-ways-do-you-know-to-draw-a-glowing-border-in-jetpack-compose-57980d049562">How Many Ways Do You Know to Draw a Glowing Border in Jetpack Compose?</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PDE-Based Wave Simulation in Jetpack Compose: Canvas vs AGSL]]></title>
            <link>https://proandroiddev.com/pde-based-wave-simulation-in-jetpack-compose-canvas-vs-agsl-58d52a88f22f?source=rss-eaf677d34c58------2</link>
            <guid isPermaLink="false">https://medium.com/p/58d52a88f22f</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[graphics-programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[animation]]></category>
            <dc:creator><![CDATA[Yuriy Skul]]></dc:creator>
            <pubDate>Wed, 11 Mar 2026 20:13:18 GMT</pubDate>
            <atom:updated>2026-03-11T20:13:18.328Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9P3qY5Fn6IFlla0U-Q4b_w.png" /></figure><p>In this article, I’ll build a 1D PDE wave simulation in Jetpack Compose, walk through performance tips and common pitfalls, and look at AGSL from a less obvious angle that is often missed at first glance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*q2lubJ_UiCti2whi-kn8wA.gif" /><figcaption>PDE Liquid Bar (Canvas / AGSL Runtime RenderEffect / AGSL-in-Canvas)</figcaption></figure><h4>Problem</h4><p>Let’s build an interactive liquid effect in Jetpack Compose: it reacts to touch, creates waves on the surface, slowly settles, and blends with real UI content like text and icons.<br>For blending, we want two behaviors: invert content colors in some areas or apply per-pixel alpha masking when content is partially covered by the wave.</p><p>The challenge is balancing visual quality and performance.<br>Effects like this can look great, but on Android they can also introduce jitter, delayed response, and extra redraw cost.</p><p>So the goal is practical: keep it responsive on real devices, reduce artifacts, and pick a rendering approach that stays stable under load.</p><h4>The 1D Wave Model</h4><p>For this effect, I use a 1D wave model based on the wave PDE (Partial Differential Equation). I won’t go into the full math derivation here and will focus on the implementation idea. In 1D, the wave is represented as a row of samples across the container width. Each sample stores vertical displacement (Y) at a specific horizontal position (X). At every frame, each point is updated from its two neighbors and its own value from the previous frame:</p><p>next[i] = (curr[i-1]+curr[i+1] — prev[i])*damping</p><p><strong>Important detail: to compute the next state, we need both the current and previous states. </strong><br> That is why <strong>the simulation keeps three buffers at the same time: prev, curr, and next</strong> (see Wave1D with three FloatArrays).<br> After each step, these buffers are rotated.</p><pre>  internal class Wave1D(samples: Int) {<br>      ...<br>      private var curr = FloatArray(n)<br>      private var prev = FloatArray(n)<br>      private var next = FloatArray(n)<br>      ...<br>  }</pre><p>Key wave parameters: <br>- samples — horizontal simulation resolution.<br>- damping — how quickly wave energy decays.<br>- yGain — visual wave amplification at render time.<br>- plotWidth — transition band width between the wave and non-wave space (hard vs soft edge).</p><p>Touches are handled as instant impulses. Each touch is clamped to valid X/Y bounds, converted to pulse strength, and distributed across nearby samples with touchPulseInfluence. We do not store touch paths; we only modify the current wave state at the moment of interaction, then continue with the same fixed-cost simulation step per frame. <strong>A key benefit of this approach is that even with many taps per second, the ongoing simulation complexity does not grow.</strong></p><pre>...<br>// Apply one touch impulse to the current wave state<br>fun inject(touchX: Float, touchYBottomUp: Float) {<br>      // 1) Normalize touch position and convert it to impulse strength<br>      val centerX = touchX.coerceIn(0.1f, 0.9f)<br>      val touchStrength = (1f - touchYBottomUp.coerceIn(0f, 1f)) * amp<br><br>      // 2) Spread that impulse across nearby wave samples<br>      // Iterate over all wave samples along X<br>      for (sampleIndex in 0 until n) {<br>          val sampleX = sampleIndex.toFloat() / (n - 1).toFloat()<br>          val influence = touchPulseInfluence(centerX, pulseWidthNorm, sampleX)<br>          if (influence != 0f) curr[sampleIndex] -= influence * touchStrength<br>      }<br>  }<br>...</pre><p>where toushPulseInflience() computes how much each sample is affected by the touch, based on distance from the touch center: maximum influence near the center, smoothly fading to zero within pulseWidthNorm</p><p>Main touch-tuning parameters: <br>- amp — impulse strength injected by touch.<br>- pulseWidthNorm — horizontal width of the touch influence zone.<br>- dragThrottleMs — injection rate limit during drag (lower value = more frequent injections).</p><p>At each frame tick, we run Wave1D.step().<br>Inside this function, we update every sample point using its neighbors and compute the next wave state.<br>After that, we swap buffer roles: the current state becomes previous, and the newly computed state becomes current.</p><pre>fun step() {<br>      for (i in 1 until n - 1) {<br>          next[i] = (curr[i - 1] + curr[i + 1] - prev[i]) * damping<br>      }<br><br>      // Swap roles: prev &lt;- curr, curr &lt;- next<br>      val oldPrev = prev<br>      prev = curr<br>      curr = next<br>      next = oldPrev<br>  }</pre><p>This way, the next frame always starts with fresh wave data instead of rebuilding arrays from scratch.</p><h4>Common Runtime Model</h4><p>So the Update-Render Loop is:</p><ul><li>Frame tick</li><li>Wave1D.step() updates wave swap buffers</li><li>draw wave (Canvas or AGSL)</li><li>Frame tick (repeat)</li></ul><p>Each LiquidBox (top and button bar) is intentionally taller than the visible bar area: the top container is about twice the top bar height, and the bottom container is about about twice the bottom bar height. Both containers overlap the scrolling content. This extra height gives the wave enough vertical space to breathe and animate naturally, while only the bar zone remains interactive.</p><p><em>Well, during development </em><strong>AGSL RenderEffect </strong>Approach<strong><em> </em></strong><em>was my favorite approach, so I was focusing on it . At the same time, I also optimized the Canvas approach, even though I was not very motivated, mainly to make sure this option was covered but the final results turned out to be different from my initial<br> expectations.</em></p><h3>Common Optimization Pitfalls and Performance Tips</h3><p><strong>State Handling (Mutable Buffers Over Immutable State):<br></strong>In typical Android/Kotlin UI, immutable state and data-class copies are often preferred. For high-frequency simulation, that approach is too expensive. Creating new objects every frame adds avoidable allocation and GC pressure, so this solver keeps mutable numeric buffers and updates them in place. That keeps per-frame work significantly cheaper.</p><p>In typical Android/Kotlin UI, immutable state and data-class copies are often preferred. For high-frequency simulation, that approach is too expensive. Creating new objects every frame adds avoidable allocation and GC pressure, so this solver keeps mutable numeric buffers and updates them in place. That keeps per-frame work significantly cheaper.</p><p><strong>Reduce simulation samples count:<br></strong>The wave solver keeps three buffers (prev, curr, next), each with length = samples. For example, with a 1024px container, you can reduce samples from 1024 to 126 to lower simulation cost.</p><p>So sample count should directly affect step() performance, because step() iterates over wave samples every frame.<br> That is exactly what the experiment showed:</p><p>At samples = <strong>126</strong>, step() took about <strong>31–43 µs (~0.03–0.04 ms)</strong>.<br>At samples = <strong>2024</strong>, it increased to about <strong>500–1050 µs (~0.5–1.05 ms) </strong>— roughly 15–25x slower, with near-linear scaling.</p><p>So yes, higher sample count clearly increases simulation cost. But even in the high-sample case, step() s<strong>tayed up to ~1 ms</strong>, which is still a relatively small part of a 16.6 ms frame budget.</p><p><strong>Interpolation:<br></strong>Because the wave is sampled, a low sample count can make the shape look stair-stepped, like a bar chart. To avoid this, interpolation should be applied during rendering.</p><ul><li>2-tap <strong>linear interpolation</strong>: low cost and usually good visual quality.</li><li>3-tap <strong>smoothing filter</strong>: smoother than linear, with a small extra cost.</li><li>4-tap <strong>cubic interpolation</strong>: smoother curves, but more expensive and harder to tune.</li></ul><p><strong>Use </strong><strong>drawWithCache over </strong><strong>remember(...):<br></strong> For both Canvas and AGSL-Canvas paths, drawWithCache is usually a better fit for render resources. <br>It keeps objects at draw-node level, such as Paint, shader instances (RuntimeShader, BitmapShader), and helper path data. When a draw modifier depends on frame-driven state (for example, frameTick), using remember(…) can recreate the draw node on every tick, which adds modifier-chain churn instead of only triggering redraw. drawWithCache keeps the draw node stable and re-runs only the draw callback, so each tick triggers redraw rather than draw-node recreation.</p><p><strong>Reduce Per-Frame Updates (Not Recommended):<br></strong>In theory, updating simulation and rendering less often should reduce frame cost. In practice (my case), it did not improve the expensive frames and introduced visible stutter. This approach creates perceived FPS drops and hurts visual quality, so <strong>it should be avoided</strong>.</p><p><strong>Avoid Too Many Heavy Animated Containers on One Screen:<br></strong>When several containers run heavy per-tick work on the same screen, frame-time spikes become much more likely. If multiple animated zones are required, try to share rendering passes or reduce overlapping expensive effects. Even when simulations remain separate, reducing pipeline overhead (extra layers/compositing) can still improve stability.</p><p><strong>Stop the Simulation When the Wave Has Settled:<br></strong> When the wave is no longer moving, there is no reason to keep ticking and redrawing the same state. You can also increase damping so the wave settles faster and the animation runs for less time.</p><p>In this project, each step() evaluates the current “energy value” (maxAbsNext) and its frame-to-frame change (maxDelta). When both stay below the rest threshold for several consecutive frames, the simulation stops running.</p><p><strong>Prefer built-in optimized rendering primitives over custom loops :<br></strong> Whenever possible, use standard GPU-optimized APIs (drawPath, shader interpolation via mix/smoothstep, and drawWithCache) instead of manual per-pixel/per-column drawing logic.</p><h4>AGSL RenderEffect</h4><p>Uses RuntimeShader through RenderEffect as a post-processing pass on the LiquidBox layer. The shader itself is straightforward: it samples a 1D wave profile, builds a per-pixel wave mask, and composites liquid<br> color with source content.</p><p>Main uniforms passed to AGSL:</p><ul><li>container size (uContainerWidthPx, uContainerHeightPx)</li><li>profile width (uProfileWidthPx)</li><li>band/thickness (uBandPx)</li><li>orientation (uIsTop)</li><li>liquid color (uWaveColor)</li><li>profile texture (waveProfile)</li></ul><p>Because we cannot run persistent PDE simulation state directly inside this shader (no shared mutable simulation buffer/output feedback loop), wave state is computed on CPU and uploaded each frame. AGSL does not<br>accept raw arrays directly, so <strong>the wave samples are packed into a 1 x N bitmap</strong> (N = sample count)</p><p>Encoding note:</p><ul><li>8-bit in one channel is possible for coarse values.</li><li>For precise per-pixel height, two channels are used (RG = 16-bit packed value), which is enough precision for screen-space wave height mapping.</li></ul><p>In this project, each wave sample height is converted to a 16-bit value before being sent to AGSL. This is handled by rememberWaveProfileArgb16(): the normalized height is quantized to 0..65535, then packed into two bitmap channels (Red = high byte, Green = low byte).<br>So the profile texture is 1 x N, and each texel stores one sample with 16-bit precision using two channels, not one.</p><p>If needed, this can be reduced to a single channel, but the gain is usually small because the bitmap dimensions stay the same.</p><p>The <strong>bigger win comes from moving interpolation to AGSL</strong>: instead of expanding data to full container width on CPU, we upload only N simulation samples. Otherwise, we would have to prepare and upload a profile with width equal to container pixels (often around 1060 in portrait on many phones).<br>Among the available AGSL interpolation options, 2-tap linear interpolation (mix) was used. This option is cheap and gives good visual quality.<br>smoothstep shaping was not used, because UI element boundaries are intentionally sharp, and a soft transition would look inconsistent with standard Android UI elements such as the top app bar and bottom app bar.</p><p>Because RuntimeShader via RenderEffect works as a post-processing pass, it allows <strong>cheap per-pixel checks during shader evaluation</strong>. Each pixel can be tested against the wave level, and top/bottom app bar UI pixels (tabs, text, buttons, icons) above the wave can be filtered out by reducing alpha (<strong>pixel-level alpha filter</strong>). This per-pixel filtering over the layer content is a key feature of the RenderEffect approach:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMTPVC1WcAEqluHwP8qOMA.jpeg" /><figcaption>Per-pixel AGSL alpha filtering (clip imitation)</figcaption></figure><p>In theory, RuntimeShader supports dynamic uniform updates via setFloatUniform. However, when it is used through RenderEffect in a Compose graphicsLayer, uniform updates alone often do not trigger redraw. As a result, <strong>RenderEffect is frequently recreated to force layer refresh, which introduces extra allocations during frame updates</strong>.</p><h4>AGSL via Canvas (RuntimeShader + Paint)</h4><p>AGSL-in-Canvas was used as a hybrid renderer: Wave1D stays on CPU, while AGSL handles final pixel shaping on GPU via Canvas shader drawing. In this setup, it reduced some RenderEffect overhead and kept frame updates more predictable, while preserving visual quality through shader-side interpolation.</p><p>The key difference from Runtime RenderEffect is that this shader is rendered as an explicit overlay layer, rather than applied as a post-processing effect.</p><p>Compared to the Runtime RenderEffect path, this AGSL-in-Canvas variant does not require recreating the shader object each frame, which keeps update flow simpler.</p><p>However, wave-boundary pixel filtering of underlying UI elements (like in the Runtime post-processing approach) is harder to implement here, because it requires additional layer/blend orchestration. This is not<br>implemented in this project.</p><p>This approach also relies on AGSL’s built-in GPU pipeline, so it remains highly optimized and is typically on par with Runtime RenderEffect. In some cases, it can even be faster.</p><h4>Classic Canvas Renderer</h4><p>In a pure Canvas renderer, the wave can be drawn as vertical drawRect columns, but this is heavier and often looks stepped. To smooth it out, you would need to increase fragment count and interpolate closer to<br>screen-pixel width, which quickly raises per-frame draw cost…</p><p>But there is a more powerful option: <strong>Path API</strong>. No extra fragment upscaling or manual interpolation is needed here. Path APIs already include built-in curve primitives (quadraticBezierTo / cubicTo), so one smooth wave path can be built and rendered in a single pass, with good visual quality and solid performance.</p><p>Another nice thing about Path API is that clipping by path is straightforward: clipPath(...) { drawContent() }. It helps solve content overlap when UI elements cross the wave boundary. In the Runtime RenderEffect approach, this was handled with per-pixel alpha filtering instead.</p><h4>Results and Comparison (HWUI Profiling)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*vlY3g0eKGHgNzk0aZLqqZw.png" /><figcaption><a href="https://developer.android.com/topic/performance/rendering/profile-gpu">HWUI Profile: Pipeline Stages (Color legend from Android documentation)</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*jLE8B0e1kKE--UWBauP8fQ.gif" /><figcaption>Profile GPU Rendering Graph</figcaption></figure><p>In my measurements, all variants stayed below the red line, but AGSL Runtime RenderEffect was the slowest.<br> The Canvas renderer performed best and stayed closer to the green line, (even with additional costs enabled (either clipPath or full-screen Difference blend via offscreen graphicsLayer for UI color inversion).</p><p>In AGSL Runtime RenderEffect mode, the blue Draw segment is mostly gone, while the orange Swap segment becomes larger. This indicates that frame cost shifts from CPU draw work to GPU present/synchronization, so<br>more time is spent waiting at eglSwapBuffers before the frame is shown.</p><p>A control test with an almost empty screen and a trivial per-frame AGSL shader (solid color only) showed similar HWUI bar heights. This suggests the main cost comes from the RuntimeShader/RenderEffect pipeline<br> itself, so extra micro-optimizations in this AGSL Runtime path are unlikely to matter much.</p><p><strong>Why did Canvas win here?<br></strong>In this case, Compose only issues draw commands, while Path building/rasterization runs in the native graphics stack (Skia/C++).<br> A Path-based wave is then rendered as geometry, mostly over the shape area. By contrast, the AGSL Runtime RenderEffect path applies shader<br>work over the whole target layer (effectively a per-pixel pass), which increases GPU present/sync cost.<br>So for this effect, drawPath turned out faster and more stable than full-layer AGSL post-processing.</p><h4>Final Takeaways</h4><ul><li>For frame-ticked, physics-heavy one-dimensional simulations without advanced pixel effects, sampling with classic Canvas Path rendering is usually the best practical choice. In this case, per-pixel AGSL<br> Runtime RenderEffect did not provide a performance win in this case.</li><li>AGSL Runtime RenderEffect can produce very powerful per-pixel visuals, and it shines when complex texturing or shader-only effects are needed. The downside is data flow: complex effects usually require complex state models, and updating/managing that state every frame can become a bottleneck. In AGSL, dynamic data is often packed into bitmaps (up to 4 channels × 8 bits per pixel) and uploaded per frame, which adds CPU/GPU transfer cost. Unlike OpenGL/Vulkan GLSL pipelines (with persistent GPU buffers and ping-pong resources), AGSL RuntimeShader does not expose writable/shared GPU buffers for simulation state. Because of that, heavy state updates stay CPU-driven and can hurt frame time.<br>A buffered-state API in AGSL would significantly improve this kind of workload.</li></ul><p><a href="https://github.com/yuriyskulskiy/android-compose-playground/tree/main/app/src/main/java/com/skul/yuriy/composeplayground/feature/liquidBar">Source code: GitHub link to the current project.</a></p><p>Thanks:)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58d52a88f22f" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/pde-based-wave-simulation-in-jetpack-compose-canvas-vs-agsl-58d52a88f22f">PDE-Based Wave Simulation in Jetpack Compose: Canvas vs AGSL</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AGSL Alpha Blur with Local Regions and Dynamic Radius (Linear and Gaussian, 17/61/101 taps)]]></title>
            <link>https://medium.com/@yuriyskul/agsl-alpha-blur-with-local-regions-and-dynamic-radius-linear-and-gaussian-17-61-101-taps-3a36198c9567?source=rss-eaf677d34c58------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a36198c9567</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[agsl]]></category>
            <category><![CDATA[blur]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Yuriy Skul]]></dc:creator>
            <pubDate>Tue, 10 Mar 2026 18:30:06 GMT</pubDate>
            <atom:updated>2026-03-22T02:33:37.202Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PpTkzR6ZD9yAiOF9se3ETA.jpeg" /><figcaption>Dynamic local Gaussian blur.</figcaption></figure><p><em>In the previous article, I started with Android’s regular blur and quickly hit two hard limits: </em><strong><em>it blurs the whole layer</em></strong><em>, and it uses </em><strong><em>one constant radius</em></strong><em> for all pixels. For metaball-like edge behavior, that is not enough.<br> The blur must be local, applied only where interaction with edges happens, and the radius must be dynamic, changing by position.<br> In this article, I build exactly that with AGSL alpha blur, compare linear and Gaussian variants, and test quality/performance tradeoffs across 17, 61, and 101 taps.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*YWCmUf2Ik6kEBszSw96aZg.gif" /><figcaption>AGSL Custom Blur (Local, Dynamic and Complex)</figcaption></figure><h4>Series Roadmap</h4><p>0. <a href="https://medium.com/@yuriyskul/agsl-text-metaball-scrolling-edges-getting-started-696d59418127">Getting Started. Metaball edges and metaball text, first look)</a><br>1. <a href="https://medium.com/@yuriyskul/text-metaball-scrolling-edges-local-overlay-with-regular-compose-modifier-blur-23b835242815">Text overlay with regular compose </a><a href="https://medium.com/@yuriyskul/text-metaball-scrolling-edges-local-overlay-with-regular-compose-modifier-blur-23b835242815">Modifier.blur(...)</a> <br>2. Custom AGSL Alpha Blur: Local and Dynamic Radius ← You are here<br>3. <a href="https://medium.com/proandroiddev/jetpack-compose-metaball-edge-effect-final-part-ac8a4cc7a425">Final working solution: Metaball edges using custom blur</a></p><p><a href="https://github.com/yuriyskulskiy/android-compose-playground/tree/main/app/src/main/java/com/skul/yuriy/composeplayground/feature/customAlphaBlur">Current article <strong>github link</strong></a><strong><br></strong><a href="https://github.com/yuriyskulskiy/android-compose-playground/tree/main/app/src/main/java/com/skul/yuriy/composeplayground/feature/customAlphaBlurRadial"><strong>Addon: </strong>Radial Dynamci local Alpha blur</a></p><h4>0. Scope and Limits of Alpha Blur</h4><ul><li>Alpha blur is not a full-color blur.<br> It blurs only the alpha channel, so it works best for content like solid text/icons on transparent background. In that case, alpha carries the shape, and blurring alpha gives the effect we need.</li><li>If a layer is fully opaque everywhere (for example, an image where all pixels have alpha = 1.0), alpha blur has almost no useful information to work with, so the result is effectively negligible for shape softening.</li><li>Another important detail: AGSL (through RenderEffect) runs on the input layer content, not on the final composited result of everything behind it.<br> So the shader sees only pixels produced inside that graphics layer subtree.</li></ul><pre>  Box {<br>      // A, B are outside the shader input<br>      AComposable()<br>      BComposable()<br><br>      Box(<br>          modifier = Modifier.graphicsLayer {<br>              renderEffect = myAgslEffect // AGSL is applied here<br>          }<br>      ) {<br>          // C, D are inside the shader input<br>          CComposable()<br>          DComposable()<br>      }<br>  }</pre><p>In this setup, AGSL receives pixels from C + D only.<br> Pixels from A + B are not part of the shader input. This is actually an advantage: it isolates the effect from unrelated background layers and visual noise, so the blur can be applied only to the target content without interference.</p><p>There are three Regular android variants:</p><ol><li>Modifier.blur()</li><li>RenderEffect.createBlurEffect()via graphicsLayer</li><li>Paint+ BlurMaskFilter on Canvas</li></ol><p>The first two are essentially the same thing. Modifier.blur() is just a Compose convenience wrapper that internally sets a RenderEffect on a graphicsLayer, while BlurMaskFilter is a different, legacy canvas path.</p><p>They both rely on the modern Android rendering pipeline (Android 12+).</p><pre>Modifier.blur() → graphicsLayer.renderEffect → RenderEffect.createBlurEffect()</pre><p>The third option, BlurMaskFilter, is different.<br> It applies a mask filter to a Paint during drawing on a Canvas. It is primarily intended for soft shadows and glow effects, not for blurring already rendered UI content. It is also considered legacy and is less optimized for full UI blur scenarios.</p><p>RenderEffect.createBlurEffect() does not implement blur in Java.<br> The actual blur is executed in native C++ code inside the Android rendering engine (HWUI / Skia), typically on the GPU.</p><p>The general idea:</p><ul><li>Content is rendered into an offscreen texture.</li><li>A blur pass (often separable Gaussian: horizontal + vertical) is applied.</li><li>The result is composited back onto the screen.</li></ul><p>The exact implementation may vary across Android versions and devices, since it depends on Skia and the GPU backend (OpenGL / Vulkan).</p><p><strong>Why a Custom AGSL Blur Won’t Be Identical:<br></strong>AGSL gives full control over the shader and allows building highly customized blur logic.<br> However, it cannot be <em>exactly</em> identical to the system blur because:</p><ul><li><strong>The internal algorithm of </strong><strong>RenderEffect is not exposed.</strong></li><li>The system may use hidden optimizations (downscaling, approximations, driver-level tricks).</li><li>GPU implementations can differ across devices.</li><li>Color space and premultiplied alpha handling may vary.</li></ul><p>A custom AGSL blur can get very close visually — and even offer more flexibility — <strong>but it will never be a byte-for-byte match with the native system blur.</strong></p><h4>1. 1 . Static AGSL Alpha Blur.</h4><p>The Modifier and RenderEffect:</p><pre>fun Modifier.alphaLinearBlur(<br>    radius: Dp,<br>    color: Color = Color.Black,<br>): Modifier = composed {<br>    if (Build.VERSION.SDK_INT &lt; 33) return@composed this<br><br>    val density = LocalDensity.current<br>    val rPx = with(density) { radius.toPx() * 0.8f }<br><br>    val effect = rememberAlphaLinearBlur17TapEffect(rPx, color)<br><br>    graphicsLayer {<br>        compositingStrategy = CompositingStrategy.Offscreen<br>        renderEffect = effect.asComposeRenderEffect()<br>    }<br>}<br><br>@RequiresApi(Build.VERSION_CODES.TIRAMISU)<br>@Composable<br>private fun rememberAlphaLinearBlur17TapEffect(radiusPx: Float, color: Color): RenderEffect {<br>    val r = max(0f, radiusPx)<br><br>    return remember(r, color) {<br>        val rtH = RuntimeShader(AlphaLinearBlur17TapAglsl).apply {<br>            setFloatUniform(&quot;uDir&quot;, 1f, 0f)<br>            setFloatUniform(&quot;uRadius&quot;, r)<br>        }<br>        val rtV = RuntimeShader(AlphaLinearBlur17TapTintAglsl).apply {<br>            setFloatUniform(&quot;uDir&quot;, 0f, 1f)<br>            setFloatUniform(&quot;uRadius&quot;, r)<br>            setFloatUniform(&quot;uColor&quot;, color.red, color.green, color.blue, color.alpha)<br>        }<br><br>        val eH = RenderEffect.createRuntimeShaderEffect(rtH, &quot;src&quot;)<br>        val eV = RenderEffect.createRuntimeShaderEffect(rtV, &quot;src&quot;)<br>        RenderEffect.createChainEffect(eV, eH)<br>    }<br>}</pre><p>This modifier builds a <strong>two-pass separable alpha blur</strong> using RenderEffect.createChainEffect(...).</p><p><strong>Shader parameters:</strong></p><ul><li>uRadius — blur radius in pixels (converted from Dp).</li><li>uDir — a float2 direction vector: <br>- (1, 0) → horizontal blur<br>- (0, 1) → vertical blur</li><li>uColor — final tint color (RGBA) applied in the second pass.</li></ul><p><strong>How it works</strong></p><p>The same blur logic is applied twice:</p><ol><li>First pass blurs alpha horizontally (uDir = (1, 0)).</li><li>Second pass blurs alpha vertically (uDir = (0, 1)) and applies tint.</li></ol><p>The tint step is mostly an optimization and architectural choice: it lets us colorize the blurred mask directly in the second pass. If tinting is not required, we can simply propagate the original RGB through both passes and only replace the alpha channel. In that case, the final pixel keeps its original color while only its alpha changes.</p><p>Alpha Blur — Pass 1 (X direction):</p><pre>private const val AlphaLinearBlur17TapAglsl = &quot;&quot;&quot;<br>uniform shader src;<br>uniform float2 uDir;<br>uniform float  uRadius; // px<br><br>half4 main(float2 p) {<br>    float stepPx = max(0.25, uRadius / 8.0);<br><br>    half s = 0.0;<br>    s += src.eval(p + uDir * (-8.0 * stepPx)).a;<br>    s += src.eval(p + uDir * (-7.0 * stepPx)).a;<br>    s += src.eval(p + uDir * (-6.0 * stepPx)).a;<br>    s += src.eval(p + uDir * (-5.0 * stepPx)).a;<br>    s += src.eval(p + uDir * (-4.0 * stepPx)).a;<br>    s += src.eval(p + uDir * (-3.0 * stepPx)).a;<br>    s += src.eval(p + uDir * (-2.0 * stepPx)).a;<br>    s += src.eval(p + uDir * (-1.0 * stepPx)).a;<br><br>    s += src.eval(p).a;<br><br>    s += src.eval(p + uDir * ( 1.0 * stepPx)).a;<br>    s += src.eval(p + uDir * ( 2.0 * stepPx)).a;<br>    s += src.eval(p + uDir * ( 3.0 * stepPx)).a;<br>    s += src.eval(p + uDir * ( 4.0 * stepPx)).a;<br>    s += src.eval(p + uDir * ( 5.0 * stepPx)).a;<br>    s += src.eval(p + uDir * ( 6.0 * stepPx)).a;<br>    s += src.eval(p + uDir * ( 7.0 * stepPx)).a;<br>    s += src.eval(p + uDir * ( 8.0 * stepPx)).a;<br><br>    half a = s / half(17.0);<br>    return half4(a, a, a, a);<br>}<br>&quot;&quot;&quot;</pre><p>Alpha Blur — Pass 2 (Y direction + optional tint)</p><pre>private const val AlphaLinearBlur17TapAglsl = &quot;&quot;&quot;<br>uniform shader src;<br>uniform float2 uDir;<br>uniform float  uRadius; // px<br><br>half4 main(float2 p) {<br>    float stepPx = max(0.25, uRadius / 8.0);<br><br>    half s = 0.0;<br>    s += src.eval(p + uDir * (-8.0 * stepPx)).a;<br>    s += src.eval(p + uDir * (-7.0 * stepPx)).a;<br>    s += src.eval(p + uDir * (-6.0 * stepPx)).a;<br>    s += src.eval(p + uDir * (-5.0 * stepPx)).a;<br>    s += src.eval(p + uDir * (-4.0 * stepPx)).a;<br>    s += src.eval(p + uDir * (-3.0 * stepPx)).a;<br>    s += src.eval(p + uDir * (-2.0 * stepPx)).a;<br>    s += src.eval(p + uDir * (-1.0 * stepPx)).a;<br><br>    s += src.eval(p).a;<br><br>    s += src.eval(p + uDir * ( 1.0 * stepPx)).a;<br>    s += src.eval(p + uDir * ( 2.0 * stepPx)).a;<br>    s += src.eval(p + uDir * ( 3.0 * stepPx)).a;<br>    s += src.eval(p + uDir * ( 4.0 * stepPx)).a;<br>    s += src.eval(p + uDir * ( 5.0 * stepPx)).a;<br>    s += src.eval(p + uDir * ( 6.0 * stepPx)).a;<br>    s += src.eval(p + uDir * ( 7.0 * stepPx)).a;<br>    s += src.eval(p + uDir * ( 8.0 * stepPx)).a;<br><br>    half a = s / half(17.0);<br>    return half4(a, a, a, a);<br>}<br>&quot;&quot;&quot;</pre><p><strong>Two-Pass Separable Alpha Blur</strong></p><p>The blur is implemented as a <strong>two-pass separable kernel</strong>.<br> We apply the same 1D blur shader twice, changing only the direction vector uDir.</p><p>In the first pass:</p><pre>uDir = (1, 0)</pre><p>This performs a <strong>horizontal blur</strong>.</p><p>In the second pass:</p><pre>uDir = (0, 1)</pre><p>This performs a <strong>vertical blur</strong>.</p><p>Because the effects are chained using RenderEffect.createChainEffect(...), the second pass operates on the output of the first one. The result is a full 2D blur produced by two cheaper 1D passes.</p><p><strong>The sampling step is defined as:</strong></p><pre>float stepPx = max(0.25, uRadius / 8.0);</pre><p>stepPx controls the spacing between blur samples in pixels.</p><ul><li>uRadius / 8.0 distributes the blur radius evenly across the kernel range (−8 … +8).</li><li>max(0.25, ...) prevents the step from becoming too small for very low radii, ensuring stable and meaningful sampling.</li></ul><p>In short, stepPx determines how far each tap samples from the center pixel.</p><pre>s += src.eval(p + uDir * (-8.0 * stepPx)).a;</pre><p>This line:</p><ul><li>Offsets the current pixel position p along the chosen axis.</li><li>Samples the source shader at that offset.</li><li>Reads only the alpha channel.</li><li>Accumulates it into the blur sum.</li></ul><p>Repeating this for all offsets from −8 to +8 produces a 1D blurred alpha value.</p><p><strong>17 Taps:</strong></p><p>The kernel spans offsets from −8 to +8, including the center sample:</p><p>8 samples left + 1 center+ 8 samples right = 17 taps</p><p>Seventeen taps provide a practical balance between smoothness and performance.</p><p>Since the blur is separable, instead of computing a full 17×17 2D kernel (289 samples), we compute: 17 + 17 = 34 total samples.</p><p><strong>Tinting vs Preserving Original Color:</strong></p><p>If tinting is enabled in the second pass, the blurred alpha mask is colorized using a uniform color.</p><p>If tinting is not required, the original RGB can be propagated through both passes while only replacing the alpha channel. In that case, the pixel retains its original color and only its transparency changes, resulting in sharp color with softened coverage.</p><p><strong>Code Optimizations:<br></strong>There are a few easy ways to reduce duplication and keep the shader code more maintainable:</p><p><strong>a) single shader source for both passes</strong><br> Instead of keeping two separate AGSL strings, the blur code can live in one shader and be reused for both passes. The pass can be selected via a uniform (e.g. uPass or uMode) and a simple switch/if:</p><ul><li>uPass = 0 → horizontal (uDir = (1, 0))</li><li>uPass = 1 → vertical (uDir = (0, 1))</li></ul><p>This keeps the math in one place and only changes parameters between passes.</p><p><strong>b) replace unrolled taps with a loop</strong><br> The 17 taps can be written as a compact loop (for i = -8..8) instead of manually unrolling each sample. This makes the shader significantly shorter and easier to tweak (tap count, radius mapping, weights). In practice, some implementations still prefer unrolling for maximum predictability and compiler friendliness, but for readability the loop form is a great option—especially in an article.</p><p>Result same script for first and second run:</p><pre>uniform shader src;<br>uniform float2 uDir;<br>uniform float  uRadius; // px<br><br>half4 main(float2 p) {<br>    float stepPx = max(0.25, uRadius / 8.0);<br><br>    half sum  = 0.0h;<br>    half sumW = 0.0h;<br><br>    // 17 taps: [-8..8]<br>    for (int i = -8; i &lt;= 8; i++) {<br>        float x = float(i) * stepPx;<br><br>        // Linear blur (box) weights: all taps equal<br>        half a = src.eval(p + uDir * x).a;<br>        sum  += a;<br>        sumW += 1.0h;<br>    }<br><br>    half outA = (sumW &gt; 0.0h) ? (sum / sumW) : 0.0h;<br><br>    // Alpha-only output (mask)<br>    return half4(0.0h, 0.0h, 0.0h, clamp(outA, 0.0h, 1.0h));<br>}</pre><p><strong>Note on loops:</strong></p><p>The taps are written using a loop for readability.<br> However, in AGSL loop bounds must be compile-time constants, and some GPU drivers may not optimize loops as predictably as unrolled code.</p><p>For maximum stability and performance consistency, taps are often manually unrolled in production shaders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*CbcGNEWo-pOZxr_WspPRqA.gif" /><figcaption>Custom 17 Taps AGSL Linear Blur</figcaption></figure><h4>1. 2. Static AGSL Gaussian Blur.</h4><p>The overall structure is almost identical to the linear blur:</p><ul><li>Two-pass separable implementation</li><li>First pass: uDir = (1, 0) (horizontal)</li><li>Second pass: uDir = (0, 1) (vertical)</li><li>Same sampling window (−8 … +8)</li><li>Same stepPx logic</li></ul><p>The key difference lies in <strong>how each sample contributes to the result</strong>.</p><p><strong>Linear vs Gaussian:<br></strong>In the linear (box) blur, every sample has equal weight.<br>The result is simply the arithmetic mean of all taps.</p><p>In Gaussian blur, each sample is multiplied by a weight computed from a Gaussian distribution:</p><pre>w = exp(-(x*x) / (2.0 * sigma * sigma));</pre><p>Here:</p><ul><li>x is the distance from the center.</li><li>sigma controls how quickly the influence falls off.</li><li>The farther a sample is from the center, the smaller its weight.</li></ul><p>This produces a smoother and more natural falloff.</p><p><strong>The Kernel:<br></strong>The blur behavior is defined by a <strong>kernel</strong>.<br>A kernel is simply a set of weights applied to neighboring samples.</p><p>For our 17-tap Gaussian blur, the 1D kernel spans:</p><pre>-8 … 0 … +8</pre><p>The central sample (x = 0) has the highest weight.<br>As distance increases, the weight decreases exponentially.</p><p>Conceptually, the kernel looks like a bell curve:</p><pre>small  →  larger  →  largest  →  larger  →  small</pre><p>After accumulating weighted samples, we normalize by dividing by the total weight (sumW). This ensures the result remains within a stable range.</p><p>Linear blur produces a flatter, more uniform softening.<br>Gaussian blur concentrates influence near the center, preserving structure while still smoothing edges.</p><p>This is why Gaussian blur generally appears more visually pleasing and natural.</p><p>First run: <em>AlphaGaussianBlur17TapAglsl</em></p><pre>niform shader src;<br>uniform float2 uDir;<br>uniform float  uRadius; // px<br><br>half4 main(float2 p) {<br>    // Android-ish mapping<br>    float sigma = max(0.001, uRadius * 0.57735);<br>    float stepPx = max(0.5, uRadius / 8.0);<br><br>    float sum = 0.0;<br>    float sumW = 0.0;<br><br>    // Unrolled 17 taps: [-8..8]<br>    float x; float w;<br><br>    x = -8.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x = -7.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x = -6.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x = -5.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x = -4.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x = -3.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x = -2.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x = -1.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br><br>    x =  0.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p).a * w;             sumW += w;<br><br>    x =  1.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x =  2.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x =  3.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x =  4.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x =  5.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x =  6.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x =  7.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x =  8.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br><br>    float a = (sumW &gt; 0.0) ? (sum / sumW) : 0.0;<br>    a = clamp(a, 0.0, 1.0);<br><br>    // Keep RGB empty; only alpha mask is meaningful for the next pass<br>    return half4(0.0, 0.0, 0.0, half(a));<br>}</pre><p>Second run for another direction <em>AlphaGaussianBlur17TapTintAglsl:</em></p><pre>half4 main(float2 p) {<br>    float sigma = max(0.001, uRadius * 0.57735);<br>    float stepPx = max(0.5, uRadius / 8.0);<br><br>    float sum = 0.0;<br>    float sumW = 0.0;<br><br>    float x; float w;<br><br>    x = -8.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x = -7.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x = -6.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x = -5.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x = -4.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x = -3.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x = -2.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x = -1.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br><br>    x =  0.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p).a * w;             sumW += w;<br><br>    x =  1.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x =  2.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x =  3.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x =  4.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x =  5.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x =  6.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x =  7.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br>    x =  8.0 * stepPx; w = exp(-(x*x) / (2.0 * sigma * sigma)); sum += src.eval(p + uDir * x).a * w; sumW += w;<br><br>    float a = (sumW &gt; 0.0) ? (sum / sumW) : 0.0;<br>    a = clamp(a, 0.0, 1.0);<br><br>    // Apply tint + alpha<br>    half outA = half(a) * half(uColor.a);<br>    return half4(uColor.rgb, outA);<br>}<br>&quot;&quot;&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Ljen5pwE70g5rOKuePR7Jw.gif" /></figure><p>The structure is almost identical to the linear blur implementation.<br> The main difference is that instead of computing a simple arithmetic average, Gaussian blur computes a <strong>weighted average</strong>, where samples closer to the center have higher influence.</p><p>The center pixel effectively has weight 1, and weights decrease smoothly as distance increases — forming the Gaussian kernel.</p><p>At larger blur <strong>radius</strong>, a visible grain or grid pattern may appear.</p><p>This happens because stepPx grows with the radius while the number of taps (17) remains fixed. As the sampling distance increases, the blur becomes undersampled, and the gaps between samples become noticeable.</p><p>In short, the kernel size stays constant while the radius increases, reducing sampling density.</p><p>This can be mitigated by <strong>increasing the tap coun</strong>t, reducing stepPx growth, or using multiple smaller-radius passes. <strong>The core issue is sampling density: larger radius requires more samples to stay smooth</strong>.</p><h4>2. Larger Radius, More Sample Taps</h4><p>Let’s compare the 17-tap Gaussian AGSL from the previous chapter with 61-tap and 101-tap variants:</p><p>61 Taps Gaussian AGSL first run and second run:</p><pre>uniform shader src;<br>uniform float2 uDir;<br>uniform float  uRadius; // px<br><br>half4 main(float2 p) {<br>    float sigma = max(0.001, uRadius * 0.57735);<br>    float stepPx = max(0.125, uRadius / 30.0);<br><br>    float sum = 0.0;<br>    float sumW = 0.0;<br><br>    for (int i = -30; i &lt;= 30; i++) {<br>        float x = float(i) * stepPx;<br>        float w = exp(-(x * x) / (2.0 * sigma * sigma));<br>        sum += src.eval(p + uDir * x).a * w;<br>        sumW += w;<br>    }<br><br>    float a = (sumW &gt; 0.0) ? (sum / sumW) : 0.0;<br>    a = clamp(a, 0.0, 1.0);<br>    return half4(0.0, 0.0, 0.0, half(a));</pre><pre>uniform shader src;<br>uniform float2 uDir;<br>uniform float  uRadius; // px<br>uniform float4 uColor;  // rgba<br><br>half4 main(float2 p) {<br>    float sigma = max(0.001, uRadius * 0.57735);<br>    float stepPx = max(0.125, uRadius / 30.0);<br><br>    float sum = 0.0;<br>    float sumW = 0.0;<br><br>    for (int i = -30; i &lt;= 30; i++) {<br>        float x = float(i) * stepPx;<br>        float w = exp(-(x * x) / (2.0 * sigma * sigma));<br>        sum += src.eval(p + uDir * x).a * w;<br>        sumW += w;<br>    }<br><br>    float a = (sumW &gt; 0.0) ? (sum / sumW) : 0.0;<br>    a = clamp(a, 0.0, 1.0);<br><br>    half outA = half(a) * half(uColor.a);<br>    return half4(uColor.rgb, outA);<br>}<br>&quot;&quot;&quot;</pre><p>101 Tap Gaussian AGSL first run and second run:</p><pre>uniform shader src;<br>uniform float2 uDir;<br>uniform float  uRadius; // px<br><br>half4 main(float2 p) {<br>    float sigma = max(0.001, uRadius * 0.57735);<br>    float stepPx = max(0.125, uRadius / 50.0);<br><br>    float sum = 0.0;<br>    float sumW = 0.0;<br><br>    for (int i = -50; i &lt;= 50; i++) {<br>        float x = float(i) * stepPx;<br>        float w = exp(-(x * x) / (2.0 * sigma * sigma));<br>        sum += src.eval(p + uDir * x).a * w;<br>        sumW += w;<br>    }<br><br>    float a = (sumW &gt; 0.0) ? (sum / sumW) : 0.0;<br>    a = clamp(a, 0.0, 1.0);<br>    return half4(0.0, 0.0, 0.0, half(a));<br>}</pre><pre>uniform shader src;<br>uniform float2 uDir;<br>uniform float  uRadius; // px<br>uniform float4 uColor;  // rgba<br><br>half4 main(float2 p) {<br>    float sigma = max(0.001, uRadius * 0.57735);<br>    float stepPx = max(0.125, uRadius / 50.0);<br><br>    float sum = 0.0;<br>    float sumW = 0.0;<br><br>    for (int i = -50; i &lt;= 50; i++) {<br>        float x = float(i) * stepPx;<br>        float w = exp(-(x * x) / (2.0 * sigma * sigma));<br>        sum += src.eval(p + uDir * x).a * w;<br>        sumW += w;<br>    }<br><br>    float a = (sumW &gt; 0.0) ? (sum / sumW) : 0.0;<br>    a = clamp(a, 0.0, 1.0);<br><br>    half outA = half(a) * half(uColor.a);<br>    return half4(uColor.rgb, outA);<br>}<br>&quot;&quot;&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*wnd45wyjJqrL2CqSW9BGVg.gif" /><figcaption>17,61 and 101 Kernel taps comparation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*tHQQWsv2qeSBm88PFvCWTw.png" /><figcaption>blur radius 16 dp</figcaption></figure><p>17 taps AGSL if fine up to 16.dp</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*L5ot5879uveWdj5gajwgnA.png" /><figcaption>blur radius 48.dp</figcaption></figure><p>17-tap AGSL looks grainy at 24+ dp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*3eyplOixiRrmTeAwKZ0XfQ.png" /><figcaption>blur radius 48.dp</figcaption></figure><p>61-tap AGSL works well for large radii.</p><p><strong>Conclusion:<br></strong>61 taps is a practical default for larger Radii.<br>A good threshold is around 24.dp+ (or roughly when artifacts become visible with 17 taps).</p><p>For very large Radii, 101 taps can produce cleaner output, but it is significantly heavier on GPU cost.<br> So in production, 17 and 61 are usually the safer choices.</p><p>Selection strategy can stay manual (chosen by the developer), or it can be automated:</p><ul><li>inside shader/render-effect setup, or</li><li>in a wrapper modifier that receives blur radius and switches tap count based on that value.</li></ul><p>From my perspective as an Android developer, it is cleaner/easier to select tap count at the modifier level, where Dp, density, and UI context are already available. The shader should receive finalized pixel-space<br> parameters, not make policy decisions.</p><h4>3. Local blur (Liniar and Gaussian):</h4><p>Lets take a look at simple marker AGSL:</p><pre>private const val ThreeZoneColorMarkerAglsl = &quot;&quot;&quot;<br>uniform shader src;<br>uniform float uHeight; // px<br>uniform float uTopPx; // px<br>uniform float uBottomPx; // px<br><br>half4 main(float2 p) {<br>    float h = max(1.0, uHeight);<br>    float topEnd = clamp(uTopPx, 0.0, h);<br>    float bottomStart = clamp(h - uBottomPx, 0.0, h);<br><br>    if (p.y &lt; topEnd) {<br>        // Top: yellow<br>        return half4(1.0, 1.0, 0.0, 1.0);<br>    } else if (p.y &gt;= bottomStart) {<br>        // Bottom: violet<br>        return half4(0.7, 0.0, 1.0, 1.0);<br>    } else {<br>        // Middle: green<br>        return half4(0.0, 1.0, 0.0, 1.0);<br>    }<br>}<br>&quot;&quot;&quot;<br><br>fun Modifier.threeZoneColorMarkerTopMiddleBottom(<br>    topOffset: Dp = 150.dp,<br>    bottomOffset: Dp = 150.dp,<br>): Modifier = composed {<br>    if (Build.VERSION.SDK_INT &lt; 33) return@composed this<br><br>    val density = LocalDensity.current<br>    val topPx = with(density) { topOffset.toPx() }<br>    val bottomPx = with(density) { bottomOffset.toPx() }<br><br>    var heightPx by remember { mutableIntStateOf(0) }<br>    val shader = remember { RuntimeShader(ThreeZoneColorMarkerAglsl) }<br>    val hasValidZones = heightPx &gt; 0 &amp;&amp; (topPx + bottomPx) &lt;= heightPx.toFloat()<br><br>    val effect = remember(heightPx, topPx, bottomPx, hasValidZones) {<br>        if (!hasValidZones) return@remember null<br>        shader.setFloatUniform(&quot;uHeight&quot;, heightPx.toFloat())<br>        shader.setFloatUniform(&quot;uTopPx&quot;, topPx)<br>        shader.setFloatUniform(&quot;uBottomPx&quot;, bottomPx)<br>        RenderEffect.createRuntimeShaderEffect(shader, &quot;src&quot;)<br>    }<br><br>    this<br>        .onSizeChanged { heightPx = it.height }<br>        .then(<br>            if (hasValidZones &amp;&amp; effect != null) {<br>                Modifier.graphicsLayer {<br>                    compositingStrategy = CompositingStrategy.Offscreen<br>                    renderEffect = effect.asComposeRenderEffect()<br>                }<br>            } else {<br>                Modifier<br>            }<br>        )<br>}</pre><p>It splits the layer height into three zones and color-marks them: top yellow, middle green, bottom violet:</p><pre>if (p.y &lt; topEnd) {<br>    // Top: yellow<br>    return half4(1.0, 1.0, 0.0, 1.0);<br>} else if (p.y &gt;= bottomStart) {<br>    // Bottom: violet<br>    return half4(0.7, 0.0, 1.0, 1.0);<br>} else {<br>    // Middle: green<br>    return half4(0.0, 1.0, 0.0, 1.0);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*RWytEv-FyDwCOY4iewieiQ.png" /><figcaption>3 zone AGSL test output</figcaption></figure><p>Using AGSL, the same approach can be applied to the static shader from Chapter 1, so blur is applied selectively only to the top and bottom zones.</p><ul><li>17 taps three zones AGSL: link to the github TODO</li><li>And gaussian 17 taps three zones AGSL:</li></ul><pre><br><br>fun Modifier.alphaGaussianBlurLocalThreeZone(<br>    radius: Dp,<br>    color: Color = Color.Black.copy(alpha = 0.99f),<br>    topOffset: Dp? = null,<br>    bottomOffset: Dp? = null,<br>): Modifier = composed {<br>    if (Build.VERSION.SDK_INT &lt; 33) return@composed this<br><br>    val density = LocalDensity.current<br>    val radiusPx = with(density) { radius.toPx() }<br><br>    var heightPx by remember { mutableIntStateOf(0) }<br><br>    val computedTopPx = with(density) { topOffset?.toPx() } ?: (heightPx * 0.3333333f)<br>    val computedBottomPx = with(density) { bottomOffset?.toPx() } ?: (heightPx * 0.3333333f)<br>    val hasValidZones = heightPx &gt; 0 &amp;&amp; (computedTopPx + computedBottomPx) &lt;= heightPx.toFloat()<br><br>    val effect = rememberAlphaGaussianBlurLocalThreeZoneEffect(<br>        radiusPx = radiusPx,<br>        heightPx = heightPx,<br>        topPx = computedTopPx,<br>        bottomPx = computedBottomPx,<br>        color = color,<br>        isValid = hasValidZones,<br>    )<br><br>    this<br>        .onSizeChanged { heightPx = it.height }<br>        .then(<br>            if (hasValidZones &amp;&amp; effect != null) {<br>                Modifier.graphicsLayer {<br>                    compositingStrategy = CompositingStrategy.Offscreen<br>                    renderEffect = effect.asComposeRenderEffect()<br>                }<br>            } else {<br>                Modifier<br>            }<br>        )<br>}<br><br>private const val AlphaGaussianBlur17TapLocalThreeZoneAglsl = &quot;&quot;&quot;<br>uniform shader src;<br>uniform float2 uDir;<br>uniform float  uRadius;   // px<br>uniform float  uHeight;   // px<br>uniform float  uTopPx;    // px<br>uniform float  uBottomPx; // px<br>uniform float4 uColor;    // rgba<br><br>float isEdgeZone(float y) {<br>    float h = max(1.0, uHeight);<br>    float topEnd = clamp(uTopPx, 0.0, h);<br>    float bottomStart = clamp(h - uBottomPx, 0.0, h);<br><br>    if (y &lt; topEnd) return 1.0;<br>    if (y &gt;= bottomStart) return 1.0;<br>    return 0.0;<br>}<br><br>half4 main(float2 p) {<br>    float edge = isEdgeZone(p.y);<br>    float r = max(0.0, uRadius);<br><br>    if (edge &lt; 0.5 || r &lt; 0.5) {<br>        half a0 = src.eval(p).a;<br>        if (uDir.x &gt; uDir.y) {<br>            return half4(0.0, 0.0, 0.0, a0);<br>        }<br>        return half4(uColor.rgb, a0 * half(uColor.a));<br>    }<br><br>    float sigma = max(0.001, r * 0.57735);<br>    float stepPx = max(0.25, r / 8.0);<br><br>    float sum = 0.0;<br>    float sumW = 0.0;<br><br>    for (int i = -8; i &lt;= 8; i++) {<br>        float x = float(i) * stepPx;<br>        float w = exp(-(x * x) / (2.0 * sigma * sigma));<br>        sum += src.eval(p + uDir * x).a * w;<br>        sumW += w;<br>    }<br><br>    half a = (sumW &gt; 0.0) ? half(sum / sumW) : half(0.0);<br>    if (uDir.x &gt; uDir.y) {<br>        return half4(0.0, 0.0, 0.0, a);<br>    }<br>    return half4(uColor.rgb, a * half(uColor.a));<br>}<br>&quot;&quot;&quot;<br><br>@RequiresApi(Build.VERSION_CODES.TIRAMISU)<br>@Composable<br>private fun rememberAlphaGaussianBlurLocalThreeZoneEffect(<br>    radiusPx: Float,<br>    heightPx: Int,<br>    topPx: Float,<br>    bottomPx: Float,<br>    color: Color,<br>    isValid: Boolean,<br>): RenderEffect? {<br>    if (!isValid || heightPx &lt;= 0) return null<br><br>    val r = max(0f, radiusPx)<br>    val h = max(1, heightPx).toFloat()<br>    val tPx = max(0f, topPx)<br>    val bPx = max(0f, bottomPx)<br><br>    return remember(r, h, tPx, bPx, color, isValid) {<br>        val rtH = RuntimeShader(AlphaGaussianBlur17TapLocalThreeZoneAglsl).apply {<br>            setFloatUniform(&quot;uDir&quot;, 1f, 0f)<br>            setFloatUniform(&quot;uRadius&quot;, r)<br>            setFloatUniform(&quot;uHeight&quot;, h)<br>            setFloatUniform(&quot;uTopPx&quot;, tPx)<br>            setFloatUniform(&quot;uBottomPx&quot;, bPx)<br>            setFloatUniform(&quot;uColor&quot;, color.red, color.green, color.blue, color.alpha)<br>        }<br>        val rtV = RuntimeShader(AlphaGaussianBlur17TapLocalThreeZoneAglsl).apply {<br>            setFloatUniform(&quot;uDir&quot;, 0f, 1f)<br>            setFloatUniform(&quot;uRadius&quot;, r)<br>            setFloatUniform(&quot;uHeight&quot;, h)<br>            setFloatUniform(&quot;uTopPx&quot;, tPx)<br>            setFloatUniform(&quot;uBottomPx&quot;, bPx)<br>            setFloatUniform(&quot;uColor&quot;, color.red, color.green, color.blue, color.alpha)<br>        }<br><br>        val eH = RenderEffect.createRuntimeShaderEffect(rtH, &quot;src&quot;)<br>        val eV = RenderEffect.createRuntimeShaderEffect(rtV, &quot;src&quot;)<br>        RenderEffect.createChainEffect(eV, eH)<br>    }<br>}</pre><p>This shader is reused for both passes.<br> The second pass is identified by the direction value (uDir = 0,1), so it must always be invoked with that exact direction to produce the tinted output correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*XfzBm-ju1B35QHFlUQT3dQ.gif" /><figcaption>Local AGSL blur applied to the top and bottom regions</figcaption></figure><p><strong>Conclusion</strong>: the goal is achieved. Blur can now be applied locally to selected zones.</p><h4>4. Dynamic Alpha Blur by Height</h4><p>The next step is to apply height-based variable blur: at the bottom edge, the blur radius is the maximum value passed as a parameter; at the top edge, it is 0, with a smooth linear transition in between:</p><p>The whole trick is in the first lines of the AGSL shader:</p><pre>half4 main(float2 p) {<br>    float h = max(1.0, uHeight);<br>    float t = clamp(p.y / h, 0.0, 1.0);<br>    float r = uMaxRadius * t;</pre><ul><li>h is the layer height (guarded from zero)</li><li>t is the normalized vertical position of the current pixel: 0 at the top, 1 at the bottom.</li><li>r is the blur radius computed per pixel, so blur is no longer constant across the layer.</li></ul><p>This is what makes the blur dynamic by height.</p><ul><li>dynamic (ByHeight) Alpha Linear Blur 17 Tap Aglsl : — — — — TODO</li><li>dynamic (ByHeight) Alpha Gaussian Blur 17 Tap Aglsl :</li></ul><pre>// ----------------------------- Public Modifier -----------------------------<br><br>fun Modifier.alphaGaussianBlurByHeight(<br>    radius: Dp,<br>    color: Color = Color.Black.copy(alpha = 0.99f),<br>): Modifier = composed {<br>    if (Build.VERSION.SDK_INT &lt; 33) return@composed this<br><br>    val density = LocalDensity.current<br>    val maxRadiusPx = with(density) { radius.toPx() }<br><br>    var heightPx by remember { mutableIntStateOf(0) }<br><br>    val effect = rememberAlphaGaussianBlurByHeightEffect(<br>        maxRadiusPx = maxRadiusPx,<br>        heightPx = heightPx,<br>        color = color<br>    )<br><br>    this<br>        .onSizeChanged { heightPx = it.height }<br>        .graphicsLayer {<br>            compositingStrategy = CompositingStrategy.Offscreen<br>            renderEffect = effect.asComposeRenderEffect()<br>        }<br>}<br><br>// ----------------------------- AGSL (Pass 1: Gaussian alpha blur by height) -----------------------------<br><br>private const val AlphaGaussianBlur17TapByHeightAglsl = &quot;&quot;&quot;<br>uniform shader src;<br>uniform float2 uDir;<br>uniform float  uMaxRadius; // px<br>uniform float  uHeight;    // px<br><br>half4 main(float2 p) {<br>    float h = max(1.0, uHeight);<br>    float t = clamp(p.y / h, 0.0, 1.0);<br>    float r = uMaxRadius * t;<br><br>    // No blur at the top (or very small radius)<br>    if (r &lt; 0.5) {<br>        half a0 = src.eval(p).a;<br>        return half4(0.0, 0.0, 0.0, a0);<br>    }<br><br>    float sigma = max(0.001, r * 0.57735);<br>    float stepPx = max(0.25, r / 8.0);<br><br>    float sum = 0.0;<br>    float sumW = 0.0;<br><br>    for (int i = -8; i &lt;= 8; i++) {<br>        float x = float(i) * stepPx;<br>        float w = exp(-(x * x) / (2.0 * sigma * sigma));<br>        sum += src.eval(p + uDir * x).a * w;<br>        sumW += w;<br>    }<br><br>    half a = (sumW &gt; 0.0) ? half(sum / sumW) : half(0.0);<br>    return half4(0.0, 0.0, 0.0, a);<br>}<br>&quot;&quot;&quot;<br><br>// ----------------------------- AGSL (Pass 2: Gaussian alpha blur + tint by height) -----------------------------<br><br>private const val AlphaGaussianBlur17TapByHeightTintAglsl = &quot;&quot;&quot;<br>uniform shader src;<br>uniform float2 uDir;<br>uniform float  uMaxRadius; // px<br>uniform float  uHeight;    // px<br>uniform float4 uColor;     // rgba<br><br>half4 main(float2 p) {<br>    float h = max(1.0, uHeight);<br>    float t = clamp(p.y / h, 0.0, 1.0);<br>    float r = uMaxRadius * t;<br><br>    if (r &lt; 0.5) {<br>        half a0 = src.eval(p).a * half(uColor.a);<br>        return half4(uColor.rgb, a0);<br>    }<br><br>    float sigma = max(0.001, r * 0.57735);<br>    float stepPx = max(0.25, r / 8.0);<br><br>    float sum = 0.0;<br>    float sumW = 0.0;<br><br>    for (int i = -8; i &lt;= 8; i++) {<br>        float x = float(i) * stepPx;<br>        float w = exp(-(x * x) / (2.0 * sigma * sigma));<br>        sum += src.eval(p + uDir * x).a * w;<br>        sumW += w;<br>    }<br><br>    half a = (sumW &gt; 0.0) ? half(sum / sumW) * half(uColor.a) : half(0.0);<br>    return half4(uColor.rgb, a);<br>}<br>&quot;&quot;&quot;<br><br>// ----------------------------- RenderEffect builder -----------------------------<br><br>@RequiresApi(Build.VERSION_CODES.TIRAMISU)<br>@Composable<br>private fun rememberAlphaGaussianBlurByHeightEffect(<br>    maxRadiusPx: Float,<br>    heightPx: Int,<br>    color: Color<br>): RenderEffect {<br>    val r = max(0f, maxRadiusPx)<br>    val h = max(1, heightPx).toFloat()<br><br>    return remember(r, h, color) {<br>        val rtH = RuntimeShader(AlphaGaussianBlur17TapByHeightAglsl).apply {<br>            setFloatUniform(&quot;uDir&quot;, 1f, 0f)<br>            setFloatUniform(&quot;uMaxRadius&quot;, r)<br>            setFloatUniform(&quot;uHeight&quot;, h)<br>        }<br><br>        val rtV = RuntimeShader(AlphaGaussianBlur17TapByHeightTintAglsl).apply {<br>            setFloatUniform(&quot;uDir&quot;, 0f, 1f)<br>            setFloatUniform(&quot;uMaxRadius&quot;, r)<br>            setFloatUniform(&quot;uHeight&quot;, h)<br>            setFloatUniform(&quot;uColor&quot;, color.red, color.green, color.blue, color.alpha)<br>        }<br><br>        val eH = RenderEffect.createRuntimeShaderEffect(rtH, &quot;src&quot;)<br>        val eV = RenderEffect.createRuntimeShaderEffect(rtV, &quot;src&quot;)<br>        RenderEffect.createChainEffect(eV, eH)<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*1f_Fx7eO5Ei0sbzavGB8nw.gif" /><figcaption>Dynamic-By-Height AGSL Blur with Radius-Based 17/61-Tap Selection</figcaption></figure><h4>5. Complex Alpha Blur (Dynamic + Local)</h4><p>By combining the approaches from Chapters 3 and 4, a complex AGSL shader can be built that solves both limitations of the standard blur: lack of local application and lack of a dynamic blur radius:</p><ul><li>Complex Linear 17 Taps Alpha Blur — todo git hub link</li><li>Complex Gaussian 17 Taps Alpha Blur — todo git hub link</li></ul><p>Locality is controlled by the radius map: in pixels where blur is not needed (the middle zone), radius is set to 0, so blur is effectively skipped there.</p><pre>un Modifier.alphaGaussianBlurLocalDynamicThreeZone(<br>    radius: Dp,<br>    color: Color = Color.Black.copy(alpha = 0.99f),<br>    topOffset: Dp? = null,<br>    bottomOffset: Dp? = null,<br>): Modifier = composed {<br>    if (Build.VERSION.SDK_INT &lt; 33) return@composed this<br><br>    val density = LocalDensity.current<br>    val maxRadiusPx = with(density) { radius.toPx() }<br><br>    var heightPx by remember { mutableIntStateOf(0) }<br><br>    val computedTopPx = with(density) { topOffset?.toPx() } ?: (heightPx * 0.3333333f)<br>    val computedBottomPx = with(density) { bottomOffset?.toPx() } ?: (heightPx * 0.3333333f)<br><br>    val effect = rememberAlphaGaussianBlurLocalDynamicThreeZoneEffect(<br>        maxRadiusPx = maxRadiusPx,<br>        heightPx = heightPx,<br>        topPx = computedTopPx,<br>        bottomPx = computedBottomPx,<br>        color = color,<br>    )<br><br>    this<br>        .onSizeChanged { heightPx = it.height }<br>        .graphicsLayer {<br>            compositingStrategy = CompositingStrategy.Offscreen<br>            effect?.let { renderEffect = it.asComposeRenderEffect() }<br>        }<br>}<br><br>/**<br> * This shader is reused for both passes.<br> * The second pass is identified by the direction value (`uDir = 0,1`),<br> * so it must always be invoked with that exact direction<br> * to produce the tinted output correctly.<br> */<br>private const val AlphaGaussianBlur17TapLocalDynamicThreeZoneAglsl = &quot;&quot;&quot;<br>uniform shader src;<br>uniform float2 uDir;<br>uniform float  uMaxRadius; // px<br>uniform float  uHeight;    // px<br>uniform float  uTopPx;     // px<br>uniform float  uBottomPx;  // px<br>uniform float4 uColor;     // rgba<br><br>float localRadius(float y) {<br>    float h = max(1.0, uHeight);<br>    float top = max(0.0, uTopPx);<br>    float bottom = max(0.0, uBottomPx);<br><br>    float midStart = top;<br>    float midEnd = max(midStart, h - bottom);<br><br>    if (y &lt; midStart) {<br>        float k = clamp(y / max(1.0, top), 0.0, 1.0);<br>        return uMaxRadius * (1.0 - k);<br>    }<br><br>    if (y &lt;= midEnd) {<br>        return 0.0;<br>    }<br><br>    float k = clamp((y - midEnd) / max(1.0, bottom), 0.0, 1.0);<br>    return uMaxRadius * k;<br>}<br><br>half4 main(float2 p) {<br>    float r = localRadius(p.y);<br><br>    if (r &lt; 0.5) {<br>        half a0 = src.eval(p).a;<br>        if (uDir.x &gt; uDir.y) {<br>            return half4(0.0, 0.0, 0.0, a0);<br>        }<br>        return half4(uColor.rgb, a0 * half(uColor.a));<br>    }<br><br>    float sigma = max(0.001, r * 0.57735);<br>    float stepPx = max(0.25, r / 8.0);<br><br>    float sum = 0.0;<br>    float sumW = 0.0;<br><br>    for (int i = -8; i &lt;= 8; i++) {<br>        float x = float(i) * stepPx;<br>        float w = exp(-(x * x) / (2.0 * sigma * sigma));<br>        sum += src.eval(p + uDir * x).a * w;<br>        sumW += w;<br>    }<br><br>    half a = (sumW &gt; 0.0) ? half(sum / sumW) : half(0.0);<br>    if (uDir.x &gt; uDir.y) {<br>        return half4(0.0, 0.0, 0.0, a);<br>    }<br>    return half4(uColor.rgb, a * half(uColor.a));<br>}<br>&quot;&quot;&quot;<br><br>@RequiresApi(Build.VERSION_CODES.TIRAMISU)<br>@Composable<br>private fun rememberAlphaGaussianBlurLocalDynamicThreeZoneEffect(<br>    maxRadiusPx: Float,<br>    heightPx: Int,<br>    topPx: Float,<br>    bottomPx: Float,<br>    color: Color,<br>): RenderEffect? {<br>    if (heightPx &lt;= 0) return null<br><br>    val r = max(0f, maxRadiusPx)<br>    val h = max(1, heightPx).toFloat()<br>    val tPx = max(0f, topPx)<br>    val bPx = max(0f, bottomPx)<br><br>    return remember(r, h, tPx, bPx, color) {<br>        val rtH = RuntimeShader(AlphaGaussianBlur17TapLocalDynamicThreeZoneAglsl).apply {<br>            setFloatUniform(&quot;uDir&quot;, 1f, 0f)<br>            setFloatUniform(&quot;uMaxRadius&quot;, r)<br>            setFloatUniform(&quot;uHeight&quot;, h)<br>            setFloatUniform(&quot;uTopPx&quot;, tPx)<br>            setFloatUniform(&quot;uBottomPx&quot;, bPx)<br>            setFloatUniform(&quot;uColor&quot;, color.red, color.green, color.blue, color.alpha)<br>        }<br><br>        val rtV = RuntimeShader(AlphaGaussianBlur17TapLocalDynamicThreeZoneAglsl).apply {<br>            setFloatUniform(&quot;uDir&quot;, 0f, 1f)<br>            setFloatUniform(&quot;uMaxRadius&quot;, r)<br>            setFloatUniform(&quot;uHeight&quot;, h)<br>            setFloatUniform(&quot;uTopPx&quot;, tPx)<br>            setFloatUniform(&quot;uBottomPx&quot;, bPx)<br>            setFloatUniform(&quot;uColor&quot;, color.red, color.green, color.blue, color.alpha)<br>        }<br><br>        val eH = RenderEffect.createRuntimeShaderEffect(rtH, &quot;src&quot;)<br>        val eV = RenderEffect.createRuntimeShaderEffect(rtV, &quot;src&quot;)<br>        RenderEffect.createChainEffect(eV, eH)<br>    }<br>}</pre><p>This shader is reused for both passes.<br> The second pass is identified by the direction value (uDir = 0,1), so it must always be invoked with that exact direction to produce the tinted output correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*_mZUsLn1He2tvQ0S_3wPzQ.gif" /><figcaption>All-in-One AGSL Blur: Local + Dynamic with automatic 17/61-tap optimization for 16+ dp radii.</figcaption></figure><p><strong>Conclusion: </strong>Now the Metaball Edges effect for scrolling text can be implemented much more easily using this complex solution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a36198c9567" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text Metaball Scrolling Edges: local overlay with regular compose Modifier.blur()]]></title>
            <link>https://medium.com/@yuriyskul/text-metaball-scrolling-edges-local-overlay-with-regular-compose-modifier-blur-23b835242815?source=rss-eaf677d34c58------2</link>
            <guid isPermaLink="false">https://medium.com/p/23b835242815</guid>
            <dc:creator><![CDATA[Yuriy Skul]]></dc:creator>
            <pubDate>Thu, 05 Mar 2026 16:33:37 GMT</pubDate>
            <atom:updated>2026-03-22T02:34:13.522Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*UmTBk27ykmgT0s08kji5bA.gif" /><figcaption>Edge effect with regular blur and many workarrounds</figcaption></figure><p><em>Here is the tutorial how NOT todo metaball edgess effet using regular Modifier.blur() with simple blur mask filter by alpha. Before looking for some advance solution I had been trying gor a while to implement it with regular compose intruments. This article is just an untiPOC. Skip and go next.</em></p><h4>Series Roadmap</h4><p>0. <a href="https://medium.com/@yuriyskul/agsl-text-metaball-scrolling-edges-getting-started-696d59418127"><em>Getting Started</em>. (metaball edges and metaball text, first look)</a><br>1. Using Standard Modifier.blur(...) <em>← you are here</em><br>2. <a href="https://medium.com/p/3a36198c9567?postPublishedType=initial">Custom AGSL Gaussian Alpha Blur: Local + Variable Radius</a><br>3. <a href="https://medium.com/proandroiddev/jetpack-compose-metaball-edge-effect-final-part-ac8a4cc7a425">Final working solution: Metaball edges using custom blur</a></p><h4>1 Simple try</h4><p>In the previous article (“Getting Started”), we explored two foundations: metaball interaction between a blob and screen edges, and key text-specific behavior under a metaball-like effect.<br> In this article, we combine those two tricks and apply them in one edge-aware scrolling text pipeline.</p><ul><li>Let’s take a regular Column with verticalScroll, place a long text block inside it, and apply blur to the Column itself.</li><li>Then, top and bottom gradient edges are overlaid on top of the text Column, each with a sample height of 56.dp.<br> The top edge gradient runs from alpha = 0.4 to 0.0, and the bottom edge gradient runs from 0.0 to 0.4 (the helper edges are outlined in red for better screenshot clarity)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*s7Ebs3TeioSbO7x_-KZCVQ.png" /><figcaption>Box with Scrolled Blurred Column and Overlaid Top/Bottom Gradient Bands</figcaption></figure><ul><li>Next, apply an alpha-threshold filter effect to the root composable that contains all these elements.<br> Since the gradient bands use a maximum alpha of 40%, set the filter threshold to 40% so those helper bands become invisible.</li></ul><p>Some screens for textStyleMaterialTheme.typography.displaymedium (45.<em>sp)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*mg4lJuCcKRA_j4-Vyhm2mg.png" /><figcaption>max gradient 0.4, alpha filter 0.4, blur R = 8.dp</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*EpTqKbmUOBuP4u62TMr-bg.png" /><figcaption>max gradient 0.4 alpha, blur R = 5</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*MH6DLNtZIann7i79eSWp0A.png" /><figcaption>max gradient and alpha filter 0.2, blur R = 6.dp</figcaption></figure><p><strong>The problem: blur is applied across the entire composable area, not selectively to specific regions. Modifier.blur(…) cannot be applied locally to only the top and bottom edges.</strong></p><p>Modifier.blur(…) blurs the entire layer it is attached to. To blur only the edges, the UI must be <strong>split into separate layers</strong> and only edge layers should be blurred, or a <strong>custom AGSL shader with local blur</strong> control should be used.</p><h4>2 Add separate overlay text local layers ( Workaround)</h4><p>In this article, this is implemented using overlay layers placed exactly where blur is needed: one at the top (where the gradient Box already exists) and one at the bottom.</p><ul><li>Add to the top and bottom helper boxes fixedHeight 56.dp with text inside.</li><li>Pass the same text string to all three text instances: the main scrollable Column text and the top and bottom local helper texts:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*4iCrp9OGLb-vjwYWYfAC6g.gif" /><figcaption>Add bottom and top overlayed text composables</figcaption></figure><ul><li>Now comes the tricky part: hoist the scrollState from the scrollable Column with the main text up to the parent, so the top and bottom overlay local texts can observe the same scrolling state:</li><li>Pass to both overlays as scrollOffsetPx=scrollState.value.toFloat() and use it for translation text: Modifier.graphicsLayer{ translationY = -topOffset — scrollOffsetPx }</li></ul><pre> val scrollState = rememberScrollState()<br><br>  Column(<br>      modifier = Modifier.verticalScroll(scrollState)<br>  ) {<br>      /* main scrolling text */<br>  }<br><br>  /* Top edge local text */<br>  Box(<br>      modifier = Modifier<br>          /* ... */<br>  ) {<br>      val topOffset = 0f<br>      val scrollOffsetPx = scrollState.value.toFloat()<br><br>      Text(<br>          text = text,<br>          modifier = Modifier<br>              .graphicsLayer { translationY = -topOffset - scrollOffsetPx }<br>              /* ... */,<br>          /* ... */<br>      )<br>  }<br><br>  /* Bottom edge local text */<br>  Box(<br>      modifier = Modifier<br>          /* ... bottom edge container modifiers ... */<br>  ) {<br>      val topOffset = parentHeightPx - edgeHeightPx<br>      val scrollOffsetPx = scrollState.value.toFloat()<br><br>      Text(<br>          text = text,<br>          modifier = Modifier<br>              .graphicsLayer { translationY = -topOffset - scrollOffsetPx }<br>              /* ... */,<br>          /* ... style/color/fontWeight ... */<br>      )<br>  }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*GCUE9boK-0R_pIHSekl9fQ.gif" /><figcaption>Overscrolling issue</figcaption></figure><p>In normal scrolling, both text layers look like one. The difference appears during overscroll, because the overlay layer does not have scrolling or overscroll behavior.</p><p><strong>Best way to fix a problem caused by one workaround is to cover it with another workaround :)</strong></p><ul><li>Disable overscroll entirely:</li></ul><pre>CompositionLocalProvider(LocalOverscrollFactory provides null) { … }</pre><ul><li>Add some blur to the top and buttom boxes with overlay texts :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*sYFYwYryRXWOpK8CJpjWNQ.gif" /><figcaption>Add blur with radius 6.dp</figcaption></figure><ul><li>Apply alpha-threshold filtering only to the top and bottom overlay text containers. No filtering is needed for the original scrolling text.</li></ul><pre>@RequiresApi(Build.VERSION_CODES.S)<br>val alphaThreshold40PercentEffect =<br>    RenderEffect.createColorFilterEffect(<br>        ColorMatrixColorFilter(<br>            ColorMatrix(<br>                floatArrayOf(<br>                    // R<br>                    1f, 0f, 0f, 0f, 0f,<br>                    // G<br>                    0f, 1f, 0f, 0f, 0f,<br>                    // B<br>                    0f, 0f, 1f, 0f, 0f,<br>                    // A&#39; = 160 * A - 16320  → threshold ≈ 40%<br>                    0f, 0f, 0f, 160f, -16320f<br>                )<br>            )<br>        )<br>    ).asComposeRenderEffect()<br><br><br>  // ...overlay text containers...<br>  modifier = Modifier<br>      .graphicsLayer {<br>          renderEffect = alphaThreshold40PercentEffect<br>      }</pre><ul><li>Add top and bottom gradient edges, as shown in Chapter 1 (“First Try”) or in the previous “Getting Started” article. Use the same maximum gradient alpha value as in alpha-threshold filtering.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*uNSepEMt98JSIeD-7WGJfg.gif" /><figcaption>blur R 4.dp</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*Qlycb1oyehBTeiWJEYfTEg.gif" /><figcaption>blur R 6.dp</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*IItgNJHy5X9WXYILQvPxIw.gif" /><figcaption>blur R 8.dp</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*08lAYYEXvDoKFvXA8CgdDA.gif" /><figcaption>blur R 12.dp</figcaption></figure><p>Here is the second issue with the regular blur modifier: above 6.dp, text can collapse into a large blob that persists across most offsets.<br> What is needed instead is a blur radius driven by y offset, so blur grows only as text approaches the top or bottom edge.</p><p><strong>Modifier.blur(…) uses one constant radius for all pixels and does not support a variable, parameter-driven per-pixel blur function</strong></p><h4>3. Reduce Constant-Blur Artifacts with a Vertical Alpha Gradient Mask (Workaround)</h4><p>A possible workaround is to apply a vertical gradient mask to the final result, reducing the visibility of large blur artifacts farther from the edge boundary.</p><p>Anyway, covering it with a linear gradient on top of a blurred layer is not the same as applying a true dynamic blur that increases linearly across the layer, but let’s try it.</p><p>Let’s add fading edges effect to the top of the top overlay box container with text and to the bottom box of the bottom overlay text:</p><pre> Composable<br>fun Modifier.gradientTopButtonEdges(<br>    topFadeHeight: Dp = 24.dp,<br>    bottomFadeHeight: Dp = 24.dp<br>): Modifier {<br>    val density = LocalDensity.current<br>    val topFadePx = with(density) { topFadeHeight.toPx() }<br>    val bottomFadePx = with(density) { bottomFadeHeight.toPx() }<br><br>    return this.gradientTopButtonEdgesPx(<br>        topFadePx = topFadePx,<br>        bottomFadePx = bottomFadePx<br>    )<br>}<br><br>fun Modifier.gradientTopButtonEdgesPx(<br>    topFadePx: Float,<br>    bottomFadePx: Float<br>): Modifier {<br>    return this<br>        .graphicsLayer(compositingStrategy = CompositingStrategy.Offscreen) // Required for blend modes to work correctly<br>        .drawWithContent {<br>            drawContent()<br><br>            if (topFadePx &gt; 0) {<br>                val topBrush = Brush.verticalGradient(<br>                    0f to Color.Black,<br>                    1f to Color.Transparent,<br>                    startY = 0f,<br>                    endY = topFadePx<br>                )<br>                drawRect(<br>                    brush = topBrush,<br>                    size = Size(size.width, topFadePx),<br>                    blendMode = BlendMode.DstIn<br>                )<br>            }<br><br>            if (bottomFadePx &gt; 0) {<br>                val bottomBrush = Brush.verticalGradient(<br>                    0f to Color.Transparent,<br>                    1f to Color.Black,<br>                    startY = size.height - bottomFadePx,<br>                    endY = size.height<br>                )<br>                drawRect(<br>                    brush = bottomBrush,<br>                    topLeft = Offset(0f, size.height - bottomFadePx),<br>                    size = Size(size.width, bottomFadePx),<br>                    blendMode = BlendMode.DstIn<br>                )<br>            }<br>        }<br>}</pre><p>Usage:</p><pre>// Top local overlay text: fade only at the top edge<br>  Box(<br>      modifier = Modifier<br>          .fillMaxWidth()<br>          .gradientTopButtonEdges(<br>              topFadeHeight = edgeHeight,<br>              bottomFadeHeight = 0.dp<br>          )<br>  ) {<br>      Text(text = text)<br>  }<br><br>  // Bottom local overlay text: fade only at the bottom edge<br>  Box(<br>      modifier = Modifier<br>          .fillMaxWidth()<br>          .gradientTopButtonEdges(<br>              topFadeHeight = 0.dp,<br>              bottomFadeHeight = edgeHeight<br>          )<br>  ) {<br>      Text(text = text)<br>  }</pre><p>For clarity, the main text is kept transparent to avoid distractions and keep focus on the effect difference in next video clips:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*DtFpZUgB6Ojsxnedo59LdA.gif" /><figcaption>blur R 8dp</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*taf92kuMEXb6YnHqfnyZUA.gif" /><figcaption>blur R 8dp with alpha Gradient Mask</figcaption></figure><p>The gradient mask improves the result, but it is still not the behavior we actually want, because covering a blurred layer with a linear gradient is not the same as applying a true dynamic blur that changes<br> progressively across the layer.<br> The result video — is the top title video of this article.</p><p><a href="https://github.com/yuriyskulskiy/android-compose-playground/tree/main/app/src/main/java/com/skul/yuriy/composeplayground/feature/metaballEdgesRegular">Github link to the current article.</a></p><h4>Conclusion</h4><p>To solve this task, the standard blur approaches have two core limitations:</p><ul><li><strong>Local</strong>: blur cannot be limited to only the required region.</li><li><strong>Constant impact</strong>: blur intensity stays uniform across the layer and cannot vary per pixel based on position or runtime parameters.</li></ul><p>I was not prepared for this when I started implementing the idea; I thought it would be easy-peasy…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ek3QrTMA95b8NpcOq4LEOw.png" /></figure><p>So the next article will focus on a custom AGSL blur with local and dynamic behavior:</p><p><a href="http://asdasd/">Custom AGSL Gaussian Alpha Blur: Local + Variable Radius</a> — comming soon</p><p>When I’m prepared, I’ll come back to this task again…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23b835242815" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AGSL Text Metaball Scrolling Edges: Getting Started]]></title>
            <link>https://medium.com/@yuriyskul/agsl-text-metaball-scrolling-edges-getting-started-696d59418127?source=rss-eaf677d34c58------2</link>
            <guid isPermaLink="false">https://medium.com/p/696d59418127</guid>
            <category><![CDATA[metaballs]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[custom-animation]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[text-effects]]></category>
            <dc:creator><![CDATA[Yuriy Skul]]></dc:creator>
            <pubDate>Mon, 16 Feb 2026 21:52:43 GMT</pubDate>
            <atom:updated>2026-03-22T02:34:49.981Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*fcE0NP8fS5tNIhi0anAOOw.gif" /><figcaption>Gooey edges &amp; metaball text basic</figcaption></figure><p><em>Most of us have seen the same scrolling patterns: an elevated top or bottom app bar with shadow, or text that fades out as it approaches screen boundaries.<br> I want something original. Something I haven’t seen before in Android apps. Instead of fading text or using an elevated Toolbar/TopAppBar, </em><strong><em>I want text to become gooey near the top and bottom bars, melt into the edge.</em></strong></p><p><em>In this article, I focus only on how to get started. I explore two basic principles that shape my idea: how to create an object dissolve effect at the edge, and take a first look at how text behaves under a metaball-like effect.</em></p><h4>Series Roadmap</h4><p>0. Getting Started. <em>← you are here</em><br>1. <a href="https://medium.com/@yuriyskul/text-metaball-scrolling-edges-local-overlay-with-regular-compose-modifier-blur-23b835242815?postPublishedType=repub">Concept Using the Standard Android Blur Modifier </a><a href="https://medium.com/@yuriyskul/text-metaball-scrolling-edges-local-overlay-with-regular-compose-modifier-blur-23b835242815?postPublishedType=repub">Modifier.blur(...)</a> (Poor result and many workarounds. )<br>2. <a href="https://medium.com/p/3a36198c9567?postPublishedType=initial">Custom AGSL Gaussian Alpha Blur: Local + Dynamic Radius</a><br>3. <a href="https://medium.com/proandroiddev/jetpack-compose-metaball-edge-effect-final-part-ac8a4cc7a425">Final working solution: Metaball-inspired text edge blending</a></p><h4>1. Interaction with Metaball Edge</h4><ul><li>Draw a black circle (the blob).</li><li>Add top and bottom vertical edge bands (their heights can be different, and this significantly affects the final visual result).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*d2-GwWu3HUH5A4WFZkFU_w.jpeg" /><figcaption>Circle shape box , top and buttom rectangle boxes</figcaption></figure><ul><li>Add blur to the circle. Modifier.blur(40.dp)</li><li>Convert the top and bottom bands into vertical alpha gradients, where alpha increases toward the screen edges.</li><li>Keep edge alpha below 1.0 (use a value between 0 and 1, e.g. 0.5).<br>Make sure your alpha threshold is not lower than the maximum edge alpha; otherwise, parts of those rectangles will remain visible after threshold filtering.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*XMre6bJTRHeTs3k-60JmtA.png" /><figcaption>add gradient and blure to objects</figcaption></figure><ul><li>Add drag behavior, allowing the blob to move beyond the parent container bounds.</li><li>Apply alpha threshold filtering.<br>As noted earlier, keep the threshold greater than or equal to the maximum alpha used in the top and bottom edge gradients.<br>(Example: if gradient alpha is from 0% to 30%, use threshold ≥ 30% to fully hide the gradient bands after effects are applied.)</li></ul><p>In this demo, I use ColorMatrix filtering to remove everything below the threshold and make everything above it fully opaque.<br>This is not mandatory. You can use AGSL alpha filtering instead (see the section “<strong>AGSL Dynamic Alpha Filtering</strong>” below).</p><p>Result demo code:</p><pre><br>@RequiresApi(Build.VERSION_CODES.S)<br>@Composable<br>internal fun DemoBlobEdgeScreen(<br>    modifier: Modifier = Modifier,<br>) {<br>    val circleRadius: Dp = 56.dp<br>    val blurRadius = 40.dp<br>    val topEdgeHeight = 156.dp<br>    val bottomEdgeHeight = 56.dp<br>    val edgeMaxAlpha = 0.5f<br>    val alphaThreshold = localAlphaThreshold50PercentEffect<br><br>    val radiusPx = with(receiver = LocalDensity.current) { circleRadius.toPx() }<br>    var containerWidth by remember { mutableFloatStateOf(0f) }<br>    var containerHeight by remember { mutableFloatStateOf(0f) }<br>    var center by remember { mutableStateOf(Offset.Zero) }<br><br>    // Initialize blob center once container size is known.<br>    // Without this, the blob starts at (0, 0) in the top-left corner.<br>    LaunchedEffect(containerWidth, containerHeight) {<br>        if (center == Offset.Zero &amp;&amp; containerWidth &gt; 0f &amp;&amp; containerHeight &gt; 0f) {<br>            center = Offset(containerWidth / 2f, containerHeight / 2f)<br>        }<br>    }<br><br>    Box(<br>        modifier = modifier<br>            .fillMaxSize()<br>            .onSizeChanged { size -&gt;<br>                containerWidth = size.width.toFloat()<br>                containerHeight = size.height.toFloat()<br>            }<br>            // Alpha threshold: keeps only dense alpha regions after blur/gradients overlap.<br>            .applyRenderEffect(alphaThreshold)<br>            .pointerInput(Unit) {<br>                detectDragGestures { change, dragAmount -&gt;<br>                    change.consume()<br>                    center += dragAmount<br>                }<br>            },<br>        contentAlignment = Alignment.TopStart<br>    ) {<br>        <br>        // Top edge gradient helper.<br>        Box(<br>            modifier = Modifier<br>                .fillMaxWidth()<br>                .height(topEdgeHeight)<br>                .align(Alignment.TopStart)<br>                // Top edge influence zone (alpha gradient).<br>                .background(<br>                    Brush.verticalGradient(<br>                        listOf(<br>                            Color.Yellow.copy(alpha = edgeMaxAlpha),<br>                            Color.Yellow.copy(alpha = 0f)<br>                        )<br>                    )<br>                )<br>        )<br><br>        // Bottom edge gradient helper.<br>        Box(<br>            modifier = Modifier<br>                .fillMaxWidth()<br>                .height(bottomEdgeHeight)<br>                .align(Alignment.BottomEnd)<br>                // Bottom edge influence zone (alpha gradient).<br>                .background(<br>                    Brush.verticalGradient(<br>                        listOf(<br>                            Color.Red.copy(alpha = 0f),<br>                            Color.Red.copy(alpha = edgeMaxAlpha)<br>                        )<br>                    )<br>                )<br>        )<br><br>        // Draggable center blob.<br>        Box(<br>            modifier = Modifier<br>                .offset {<br>                    IntOffset(<br>                        (center.x - radiusPx).roundToInt(),<br>                        (center.y - radiusPx).roundToInt()<br>                    )<br>                }<br>                .size(circleRadius * 2)<br>                // Blur spreads alpha field around the blob.<br>                .blur(blurRadius, edgeTreatment = BlurredEdgeTreatment.Unbounded)<br>                .background(Color.Black, shape = CircleShape)<br>        )<br>    }<br>}<br><br>/**<br> * Local copy for article snippet: alpha threshold at ~50%.<br> */<br>@RequiresApi(Build.VERSION_CODES.S)<br>private val localAlphaThreshold50PercentEffect =<br>//    import android.graphics.RenderEffect<br>    RenderEffect.createColorFilterEffect(<br>        ColorMatrixColorFilter(<br>            ColorMatrix(<br>                floatArrayOf(<br>                    // R<br>                    1f, 0f, 0f, 0f, 0f,<br>                    // G<br>                    0f, 1f, 0f, 0f, 0f,<br>                    // B<br>                    0f, 0f, 1f, 0f, 0f,<br>                    // A&#39; = 160 * A - 20400 -&gt; threshold ~50%<br>                    0f, 0f, 0f, 160f, -20400f<br>                )<br>            )<br>        )<br>    ).asComposeRenderEffect()<br><br>/**<br> * Local copy for article snippet: apply RenderEffect via offscreen layer.<br> */<br>//import androidx.compose.ui.graphics.RenderEffect as ComposeRenderEffect<br>private fun Modifier.applyRenderEffect(<br>    effect: ComposeRenderEffect,<br>    clip: Boolean = true,<br>    compositingStrategy: CompositingStrategy = CompositingStrategy.Offscreen,<br>): Modifier = graphicsLayer {<br>    this.compositingStrategy = compositingStrategy<br>    this.clip = clip<br>    renderEffect = effect<br>}</pre><p>Result demo video:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*1jjkpN1YTbHHVJTWBjfpvA.gif" /><figcaption>Running current snipet</figcaption></figure><p>The difference in how the circle merges with the top and bottom bars is caused by the different heights of their gradient bands: the top (yellow) band has a height of 156.dp, while the bottom (red) band has a height of 56.dp.</p><p>The yellow and blue tints remain visible.<br> Using AGSL script for alpha filtering instead of a ColorMatrix provides greater control over the output color. A fully transparent color or white can be returned for alpha 0, and black for alpha 1. In this case, no color artifacts remain.</p><p><a href="https://github.com/yuriyskulskiy/android-compose-playground/tree/main/app/src/main/java/com/skul/yuriy/composeplayground/feature/metaballEdgesAndText/tabs/edge">github Source code: Gooey Edge Screen</a></p><h4>2.Gooey Text Effect</h4><p>With text, the same principle still works, but the result looks quite messy. As the blur radius grows and the alpha threshold decreases, glyphs begin to merge into themselves.</p><p>A practical setup is:</p><ul><li>apply blur to the Text itself</li><li>then apply padding so the blur is not clipped by text bounds.</li><li>Even though modifiers are written in order, if you apply both effects in the same node, you should place the alpha threshold modifier first and blur modifier after it.<br> The same rule applies to chained effects: the effect that you define first is the one that runs last.</li><li>Another approach is: apply blur to the Text, and apply the alpha threshold effect to its parent composable.</li></ul><pre>• @Composable<br>  fun MetaballTextNode(<br>      text: String,<br>      alphaThresholdEffect: RenderEffect,<br>      blurRadius: Dp,<br>      modifier: Modifier = Modifier,<br>  ) {<br>      // Parent: alpha-threshold render effect<br>      Box(<br>          modifier = modifier<br>              .wrapContentSize()<br>              .graphicsLayer {<br>                  compositingStrategy = CompositingStrategy.Offscreen<br>                  clip = true<br>                  renderEffect = alphaThresholdEffect<br>              }<br>      ) {<br>          // Child: blur on text<br>          Text(<br>              text = text,<br>              modifier = Modifier<br>                  .blur(blurRadius, edgeTreatment = BlurredEdgeTreatment.Unbounded)<br>                  .padding(horizontal = 16.dp, vertical = 8.dp),<br>              color = Color.Black,<br>              style = MaterialTheme.typography.headlineLarge<br>          )<br>      }<br>  }</pre><p><strong>AGSL dynamic alpha filtering:</strong></p><p>I dynamically change both the blur radius and the alpha threshold value.<br> For convenience, I do not use a ColorMatrix-based alpha filter. Instead, I use an AGSL runtime shader that receives live alpha threshold updates from the UI and and applies them directly in the render pipeline as a shader parameter:</p><pre> private const val AlphaThresholdAglsl = &quot;&quot;&quot;<br>  uniform shader src;<br>  uniform float uThreshold; // 0..1<br><br>  half4 main(float2 p) {<br>      half4 c = src.eval(p);<br>      float m = step(uThreshold, c.a);  // a &gt;= threshold ? 1 : 0<br>      return half4(c.rgb * m, m);<br>  }<br>  &quot;&quot;&quot;<br><br>  @Composable<br>  fun rememberAlphaThresholdAgslEffect(threshold01: Float): ComposeRenderEffect? {<br>      if (Build.VERSION.SDK_INT &lt; Build.VERSION_CODES.TIRAMISU) return null<br><br>      val t = threshold01.coerceIn(0f, 1f)<br>      if (t &lt;= 0f) return null<br><br>      val shader = remember { RuntimeShader(AlphaThresholdAglsl) }<br>      shader.setFloatUniform(&quot;uThreshold&quot;, t)<br><br>      return remember(shader) {<br>          RenderEffect.createRuntimeShaderEffect(shader, &quot;src&quot;).asComposeRenderEffect()<br>      }<br>  }</pre><p>Then apply it as usual to the container node:</p><pre>Modifier.applyRenderEffect(effect = alphaEffect, clip = true)</pre><p>step(uThreshold,c.a)is a threshold function. It returns:</p><ul><li>0.0 if c.a &lt; uThreshold</li><li>1.0 if c.a &gt;= uThreshold</li></ul><p>The alpha filter shader can also be written in a simpler, more familiar style.</p><pre> <br>  uniform shader src;        // Input shader: the already-rendered source layer.<br>  uniform float uThreshold;  // Alpha cutoff in range [0..1].<br><br>  half4 main(float2 p) {     // p: current pixel position.<br>      half4 c = src.eval(p); // c: source pixel color at p (r, g, b, a).<br><br>      float alpha = c.a;     // alpha: source alpha channel of this pixel.<br>      bool keep = alpha &gt;= uThreshold; // keep: true if pixel passes threshold.<br><br>      if (keep) {<br>          // Keep original RGB, force output alpha to 1.0 (fully opaque).<br>          return half4(c.rgb, 1.0);<br>      } else {<br>          // Drop pixel (fully transparent).<br>          return half4(0.0, 0.0, 0.0, 0.0);<br>      }<br>  }</pre><p>Next script gives a soft boundary instead of a hard cut. This is because smoothstep(…) does not jump directly from 0 to 1 like step(…). Pixels near the threshold get partial mask values (e.g., 0.2, 0.5, 0.8) instead of only 0 or 1.<br> That creates anti-aliased, soft edges instead of a sharp cut line. I don’t use it.</p><pre>  uniform shader src;<br>  uniform float uThreshold; // center of transition, 0..1<br>  uniform float uSoftness;  // transition width, e.g. 0.03..0.15<br><br>  half4 main(float2 p) {<br>      half4 c = src.eval(p);<br>      float alpha = c.a;<br><br>      // Soft threshold instead of hard step:<br>      // below (threshold-softness) -&gt; 0<br>      // above (threshold+softness) -&gt; 1<br>      // in between -&gt; smooth interpolation<br>      float m = smoothstep(<br>          uThreshold - uSoftness,<br>          uThreshold + uSoftness,<br>          alpha<br>      );<br><br>      // Keep original color, scale visibility smoothly<br>      return half4(c.rgb, m);<br>  }</pre><p>Let’s look at the visual behavior when we dynamically change the text blur radius and alpha-threshold value at runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*wq7pGgrLAD9xG6QZaG3Qtg.gif" /><figcaption>changing blur radius and alpha filter value</figcaption></figure><p><a href="https://github.com/yuriyskulskiy/android-compose-playground/tree/main/app/src/main/java/com/skul/yuriy/composeplayground/feature/metaballEdgesAndText/textScreen">Github link to this text metaball screen with sliders</a></p><h4>3. Metaball text transition</h4><p>It does not look great because the text starts merging into itself and turns into a dense black blob.</p><p>But this behavior can be useful for text replacement as a text morph effect.<br> With a fixed alpha threshold, animate the blur radius from 0 (no blur) to a chosen maximum, swap the text while it appears as a blob, and then animate the blur radius back to 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*V-GdOTYcyY7CEwAryQ2u0Q.gif" /><figcaption>Metababall text transformation tune</figcaption></figure><p>For specific text sizes, you can tune animation parameters mainly the max blur radius and alpha-threshold values to get one of three behaviors:</p><ol><li>The text turns into a big black mono blob and then morphs into new text.</li><li>The text turns into a blob, then the blob gradually shrinks and disappears (this usually requires a larger max blur radius than case 1), after that a new blob appears and transforms into the new text.</li><li>With higher alpha-threshold values and lower blur, the text melts and disappears almost immediately (no blobbing phase) and new text appears in its place.</li></ol><p><a href="https://github.com/yuriyskulskiy/android-compose-playground/tree/main/app/src/main/java/com/skul/yuriy/composeplayground/feature/metaballEdgesAndText/tabs/text">Github Link to this screen</a></p><p><a href="https://github.com/yuriyskulskiy/android-compose-playground/tree/main/app/src/main/java/com/skul/yuriy/composeplayground/feature/metaballEdgesAndText">Link to the whole article feature</a></p><p>Thanks:)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=696d59418127" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compose AGSL Shader: Gooey Outline Metaball Effect with Transparent Background]]></title>
            <link>https://medium.com/@yuriyskul/compose-agsl-shader-gooey-outline-metaball-effect-with-transparent-background-cb8b0e72286c?source=rss-eaf677d34c58------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb8b0e72286c</guid>
            <dc:creator><![CDATA[Yuriy Skul]]></dc:creator>
            <pubDate>Sun, 01 Dec 2024 21:11:53 GMT</pubDate>
            <atom:updated>2024-12-01T21:11:53.686Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*sTO1Btb7Di56_kZK9JKJkA.gif" /><figcaption>Filtering Points by Alpha Value, Marker Color and Calculated Brightness</figcaption></figure><p>This article explores how to create a <strong>metaball effect</strong> with a simple interaction between two circular shapes. <strong>The metaball shape is outlined with a border while the background remains completely transparent</strong>, ensuring the visibility of the underlying content. Icons inside the metaballs stay visible. This effect is achieved using an advanced <strong>AGSL shader</strong> applied to the entire container, combined with an applied blur effect for each interacting element.</p><p><strong>The concept</strong> of creating a <strong>transparent bordered metaball background with an outline effect</strong> can be found here: Chaining Blur and AGSL Runtime RenderEffects to Create Transparent Metaball Backgrounds with Outline Stroke Borders in Jetpack Compose.</p><p>Gooey Metaball Effect for Circle Buttons:</p><ul><li><strong>Part 1</strong> : <a href="https://medium.com/@yuriyskul/gooey-metaball-effects-on-android-with-jetpack-compose-blurring-and-alpha-filtering-concepts-63f1cf879257">Gooey (Metaball) Effects on Android with Jetpack Compose: Blurring and Alpha Filtering Concepts Across All API Levels.</a></li><li><strong>Part 2</strong>: <a href="https://medium.com/@yuriyskul/compose-gooey-metaball-button-effect-fixing-blur-mask-issues-on-pre-android-10-devices-with-d8f3fadc2680">Compose Gooey (Metaball) Button Effect: Fixing Blur Mask Issues on Pre-Android 10 Devices with Gradient Halo and Icon Simplification.</a></li><li><strong>Part 3</strong>: <a href="https://medium.com/@yuriyskul/jetpack-compose-gooey-metaball-interaction-using-agsl-shader-and-blur-fixing-coloring-issues-c70affdcde0f">Jetpack Compose: Gooey (Metaball) Interaction Using AGSL Shader and Blur — Fixing Coloring Issues.</a></li><li><strong>Part 4</strong>: Current.</li></ul><h4>Requirements:</h4><ul><li><strong>Opaque Border</strong>: The metaball shape should have an opaque border with a specific color, such as <strong>Black</strong>.</li><li><strong>Transparent Inner Background</strong>: The inner background of the metaballs should be fully transparent, ensuring that the overall section background remains completely unaffected and visible.</li><li><strong>Visible Button Icons</strong>: Icons inside the metaballs must remain fully <strong>opaque</strong> with a defined color and visible.</li><li><strong>Handling Collapsed Metaballs</strong>: When the metaballs collapse to a single point, only the <strong>topmost icon</strong> should remain visible, ensuring clarity in the collapsed state.</li></ul><p>Let’s start with the code of the first AGSL basic example from <a href="https://medium.com/@yuriyskul/gooey-metaball-effects-on-android-with-jetpack-compose-blurring-and-alpha-filtering-concepts-63f1cf879257"><strong>Part 1</strong></a>, where we applied an <strong>AGSL shader effect</strong> to the parent <strong>MetaballBox</strong> and added a blur effect to each circular button :</p><p>As I described in the <a href="https://medium.com/@yuriyskul/chaining-blur-and-agsl-runtime-rendereffects-to-create-transparent-metaball-backgrounds-with-15680ad1e1a9"><strong>the concept of creating a transparent bordered metaball background</strong></a>, the idea of creating a border for the metaball involves using a <strong>threshold transparency range</strong> for filtering inside the AGSL script. Pixels with transparency values falling within the defined range are set to a <strong>fully opaque color</strong>, while all other pixels are made <strong>completely transparent</strong>, creating a sharp and well-defined border effect.</p><p>This is not the primary focus of the current article. However, since the metaball shapes contain opaque icons inside, certain issues arise. To address these, I explore some workarounds and tricks to satisfy the requirements outlined above in this article.</p><h3>AGSL: Investigating Color Test</h3><p>Let’s run the test shader and assign a specific color to each point based on its input <strong>alpha</strong> value. The shader logic applies the following rules:</p><ul><li><strong>If alpha = 0.0</strong>:<br>The point is <strong>fully transparent</strong> and is colored <strong>Yellow</strong> for debugging purposes.</li><li><strong>If alpha &lt; cutoff_min</strong>:<br>The point lies in the <strong>inner region</strong> of the metaball and is colored <strong>Green</strong> to differentiate it.</li><li><strong>If alpha is between cutoff_min and cutoff_max</strong>:<br>The point is part of the <strong>border region</strong> and is colored <strong>Black</strong>, marking the transition zone.</li><li><strong>If alpha &gt; cutoff_max but less than 1.0</strong>:<br>The point lies in the <strong>outer blending region</strong>, where transparency starts fading. It is colored <strong>Blue</strong> to signify this range.</li><li><strong>If alpha = 1.0</strong>:<br>The point is <strong>fully opaque</strong> and is colored <strong>Red</strong> to mark its maximum opacity.</li></ul><p>cutoff_min = 0.5f <br>cutoff_max = 0.6f</p><pre>@Language(&quot;AGSL&quot;)<br>const val ShaderSource_outlined_color_test_1 = &quot;&quot;&quot;<br>    uniform shader composable;<br>    <br>    uniform float cutoff_min; // Minimum cutoff value for transparency<br>    uniform float border_thickness; // Thickness of the border<br>    uniform float3 rgbColor;  // Custom RGB color (not directly used in this logic)<br>    <br>    half4 main(float2 fragCoord) {<br>        half4 color = composable.eval(fragCoord);<br><br>        // Calculate cutoff_max dynamically using border_thickness<br>        float cutoff_max = cutoff_min + border_thickness;<br><br>        // If alpha is exactly 0.0 (fully transparent), set it to yellow<br>        if (color.a == 0.0) {<br>            color.rgb = half3(1.0, 1.0, 0.0); // Yellow for fully transparent<br>        }<br>        // If alpha is below the minimum cutoff, make it green<br>        else if (color.a &lt; cutoff_min) {<br>            color.rgb = half3(0.0, 1.0, 0.0); // Green<br>        } <br>        // If alpha is within the cutoff range (border area), make it black<br>        else if (cutoff_min &lt;= color.a &amp;&amp; color.a &lt;= cutoff_max) {<br>            color.rgb = half3(0.0, 0.0, 0.0); // Black<br>        } <br>        // If alpha is above the maximum cutoff but less than fully opaque (outer area), make it blue<br>        else if (cutoff_max &lt; color.a &amp;&amp; color.a &lt; 1.0) {<br>            color.rgb = half3(0.0, 0.0, 1.0); // Blue<br>        } <br>        // Fully opaque case where alpha = 1, make it red<br>        else {<br>            color.rgb = half3(1.0, 0.0, 0.0); // Red<br>        }<br><br>        // Ensure alpha is fully opaque for all cases<br>        color.a = 1.0;<br><br>        return color;<br>    }<br>&quot;&quot;&quot;</pre><p>The result when blur radius = 16.dp (metaball size = 100.dp)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*f0t_6j6AZqr74cWtWWTkbQ.gif" /><figcaption>Blur radus 16.dp (R = 50.dp)</figcaption></figure><p>As mentioned earlier, the focus of this article is not on creating the border (the black area) but on addressing the additional requirements related to the transparent part inside while keeping the icon opaque. The challenge lies in filtering by transparency to determine whether a given point belongs to the icon or the background.</p><p>But before solving this, let’s first understand why we see a red circle inside (a fully opaque pixel).</p><p>If we have a fully <strong>opaque</strong> circle of a certain color with a radius of 50.dp and apply a blur effect with a very small radius (1–2 px), the result will show that the fully opaque circle becomes slightly smaller than the original 50.dp radius. To emphasize, by “fully opaque circle,” I mean the set of points within the circle where the alpha value is exactly <strong>1.0</strong> (fully opaque), while points with alpha values less than <strong>1.0</strong> (semi-transparent or fully transparent) are not considered part of this circle. The greater the blur radius, the smaller the resulting fully opaque circle. Essentially, the blur performs a softening or spreading effect that reduces the size of the opaque circle after the effect.</p><p>What happens if the blur radius exceeds the radius of the opaque circle? In this case, no fully opaque pixels will remain within the circle, as the blur will completely disperse the opacity across the area, leaving only semi-transparent pixels.</p><p>Indeed, to completely blur out a fully opaque circle and remove all opaque pixels, we need to apply a blur radius greater than Metaball Circle Shape’s<strong> Radius / 2</strong>.</p><p>In this case, the metaball background will no longer contain any fully opaque pixels. However, since the icon is rendered on a separate layer (see the implementation of <strong>MetaballBox</strong>) to which the blur is not applied, the opacity of the icon’s pixels will remain unchanged at <strong>alpha = 1.0</strong>.</p><p>Metaball Circular Button = 100.dp so R = 50.dp. <br>Let’s set blur radius greater then = R/2+1.dp = 25.dp</p><p>For a blur radius of <strong>25.dp</strong>, a small inner opaque point will still exist. To ensure no fully opaque pixels remain, let’s set the blur radius to <strong>26.dp</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*9xZ9Py3k9Dyd52lpF74T3g.gif" /><figcaption>Blur radius 26.dp (R = 50.dp)</figcaption></figure><p>Getting closer! In the expanded state, we can filter the icon by using alpha = 1. However, when the buttons are in a collapsed state, the layers of blurred metaballs have a <strong>cumulative effect</strong>, and the resulting area with fully opaque pixels becomes larger at the given blur radius. I’m not sure about the exact formula for this calculation, and it’s not particularly important since I’ll propose a different solution later in the article. For now, let’s apply a <strong>workaround</strong> by increasing the blur radius even further.</p><p>Aplly Blur Radius = 36.dp:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*zyEJpSm3eq9ixMPbj6my5w.gif" /><figcaption>Blur Radus 36.dp (R = 50.dp)</figcaption></figure><h3>Simple AGSL: Filtering Areas by Alpha Value</h3><p>So, let’s set the input RGB color and alpha = 1 for the <strong>Red</strong> area (<strong>Icon</strong>) and the <strong>Black</strong> area (<strong>Border</strong>).<br>And apply transparency (alpha = 0) to all other sections. But there is one little moment:<br>In my example, I use Black as the color for the Circular buttons, but it’s important to note that Black is the “ZERO” color (0, 0, 0). If the Circular Button background color that is going to blurred were any non-”zero” color , such as Green, the blurred semi-transparent areas that we aim to make fully transparent by setting the alpha channel to 0 would still contribute to the blending effect. This blending effect occurs because the color components (RGB) remain non-zero, leading to an unintended visible result, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*BXNddgNOlwNZqNvBJVdCZQ.png" /><figcaption>Green background circular buttons example.</figcaption></figure><p>So, wherever we want a pixel to be completely transparent and ensure that the <strong>background layer remains unaffected without side effects</strong>, we should not only set alpha = 0 but also assign the <strong>&quot;ZERO&quot; RGB color</strong> as Black (0, 0, 0).</p><p>Previously, I used a border thickness of <strong>0.1f</strong>. To make the border thinner, let’s reduce it to <strong>0.05f</strong>.</p><pre>@Language(&quot;AGSL&quot;)<br>const val ShaderSource_outlined_simple = &quot;&quot;&quot;<br>    uniform shader composable;<br>    <br>    uniform float cutoff_min; // Minimum cutoff value for transparency<br>    uniform float border_thickness; // Thickness of the border<br>    uniform float3 rgbColor;  // RGB color passed as parameter<br>    <br>     // Constant for black (zero) RGB color<br>    const half3 BLACK_MASK_RGB = half3(0.0, 0.0, 0.0);<br>    <br>    half4 main(float2 fragCoord) {<br>        half4 color = composable.eval(fragCoord);<br>        <br>        // Calculate cutoff_max dynamically using border_thickness<br>        float cutoff_max = cutoff_min + border_thickness;<br><br>        // If alpha is exactly 0.0 (fully transparent), do nothing<br>        if (color.a == 0.0) {<br>            // Do nothing<br>        }<br>        // If alpha is below the minimum cutoff,<br>        // make it fully transparent and black<br>        else if (color.a &lt; cutoff_min) {<br>            color.rgb = BLACK_MASK_RGB; // Set to black<br>            color.a = 0.0; // Fully transparent<br>        } <br>        // If alpha is within the cutoff range (border area), <br>        // make it the custom color<br>        else if (cutoff_min &lt;= color.a &amp;&amp; color.a &lt;= cutoff_max) {<br>            color.rgb = rgbColor; // Set to custom color<br>            color.a = 1.0; // Fully opaque<br>        } <br>        // If alpha is above the maximum cutoff but less than <br>        //  fully opaque (outer area), make it fully transparent and black<br>        else if (cutoff_max &lt; color.a &amp;&amp; color.a &lt; 1.0) {<br>            color.rgb = BLACK_MASK_RGB; // Set to black<br>            color.a = 0.0; // Fully transparent<br>        } <br>        // Fully opaque case where alpha = 1 (Icon area),<br>        // make it the custom color<br>        else {<br>            color.rgb = rgbColor; // Set to custom color<br>            color.a = 1.0; // Fully opaque<br>        }<br><br>        return color;<br>    }<br>&quot;&quot;&quot;</pre><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*s5cJYscet9Gr2Pzoil7WvA.gif" /><figcaption>Simple AGSL: filters areas by alpha value only</figcaption></figure><p>Since the inner background is transparent, we have to fix the <strong>overlapping icons issue</strong>. A quick solution is to hide the icon of the button below while keeping the icon of the button on top visible.</p><p>We can track the buttons’ offsets and, when the offset becomes less than <strong>20.dp</strong>, set the visibility state for the icon below to <strong>false</strong>. Conversely, set it to <strong>true</strong> when the offset is greater than <strong>20.dp</strong>.</p><p>For optimization, wrap this logic inside a <strong>derivedStateOf</strong>. Additionally, wrap the button’s icon inside <strong>AnimatedVisibility</strong>. Alternatively, you can try changing the alpha tint color manually based on the offset between buttons.</p><p>However, if we expect the visibility transition to be smooth, this approach won’t work. In the next snippet, I have set the expanding animation duration to <strong>7 seconds</strong> and the hiding animation to <strong>4 seconds</strong>. But due to the AGSL filtering by alpha, as soon as the alpha of the icon gradually drops below <strong>1</strong>, it will immediately blend into full transparency. During the expanding animation, the icon will not fade in gradually — it will remain invisible until the end of the <strong>4-second animation</strong>. At that point, when the AnimatedVisibility container sets its alpha to fully opaque (alpha = 1), the icon will pop in immediately.</p><pre>@Composable<br>fun ExampleAGSLOutlineContent(<br>    modifier: Modifier = Modifier<br>) {<br>        var isExpanded by remember { mutableStateOf(false) }<br>        val offsetDistance = (80).dp<br>        val buttonOffset by animateDpAsState(<br>            targetValue = if (isExpanded) offsetDistance else 0.dp,<br>            animationSpec = tween(durationMillis = 7000)<br>        )<br><br>        val color = Color.Black<br><br>        //test visibility start<br>        var isVisible by remember { mutableStateOf(false) } // Another state for visibility<br>        // Derived state to update visibility based on buttonOffset<br>        val derivedVisibility = remember(buttonOffset) {<br>            derivedStateOf { buttonOffset &gt; 40.dp }<br>        }<br><br><br>        // Observe derived state and update visibility<br>        LaunchedEffect(derivedVisibility.value) {<br>            isVisible = derivedVisibility.value<br>        }<br><br>//        val blurRadius = 16.dp<br>//        val blurRadius = 26.dp<br>        val blurRadius = 36.dp<br><br><br>        OutlineShaderMetaballBox(<br>            modifier = modifier,<br>            color = color<br>        ) {<br><br>            Box(<br>                contentAlignment = Alignment.Center,<br>                modifier = Modifier<br>                    .fillMaxWidth()<br>                    .padding(vertical = 24.dp)<br>            ) {<br><br>                BlurCircularButton(<br>                    Modifier.offset { IntOffset(x = -buttonOffset.roundToPx(), y = 0) },<br>                    onClick = { isExpanded = !isExpanded },<br>                    color = color,<br>                    blur = blurRadius,<br>                ) {<br><br>                    AnimatedVisibility(<br>                        visible = isVisible,<br>                        enter = fadeIn(animationSpec = tween(durationMillis = 4000)),<br>                        exit = fadeOut(animationSpec = tween(durationMillis = 4000)),<br>                    ) {<br>                        Icon(<br>                            modifier = Modifier.size(28.dp),<br>                            imageVector = Icons.Filled.Delete,<br>                            contentDescription = null,<br>                            tint = color,<br>                        )<br>                    }<br>                }<br>                BlurCircularButton(<br>                    Modifier<br>                        .offset { IntOffset(x = +buttonOffset.roundToPx(), y = 0) },<br>                    onClick = { isExpanded = !isExpanded },<br>                    color = color,<br>                    blur = blurRadius,<br>                ) {<br>                    Icon(<br>                        modifier = Modifier.size(28.dp),<br>                        imageVector = Icons.Filled.Build,<br>                        contentDescription = null,<br>                        tint = color,<br>                    )<br>                }<br>            }<br>        }<br>}</pre><p>Blinking, Not Smooth Icon Visibility Transition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*QmmZVzScXVjnTz5ebteIiw.gif" /><figcaption>AGSL Alpha filtering breakes AnimatedVisibility transition</figcaption></figure><p>For fast expand/collapse animation durations and visibility transition durations, like <strong>150ms</strong> or <strong>300ms</strong>, this issue may not be noticeable and could work just fine.</p><h4>Pros and Cons of the Current Solution</h4><h4>Pros:</h4><ul><li>Simplicity of implementation: The AGSL script is straightforward, relying solely on the alpha channel of the input pixel color for filtering.</li></ul><h4>Cons:</h4><ul><li>There’s a strict dependency on the minimum blur radius. The more elements that merge into one, the harder it becomes to calculate or experimentally determine the minimum acceptable blur radius for a stable implementation. This makes the approach unreliable and unsuitable for a robust, stable implementation.</li><li>Due to the specifics of alpha-channel-based filtering in the AGSL script, smooth appearance and disappearance of icons is challenging.</li><li>As the number of elements involved in the metaball interaction increases, and the physics of expanding gets more complex, this leads to difficulties in determining and implementing the exact moment when icons should appear or disappear, further complicating control and the overall logic.</li></ul><p>Let’s find some better solution:</p><h3>Advansed AGSL: Filtering Areas by Alpha Value and Marker Color.</h3><p>Let’s roll back to the small blur radius 16.dp again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*AMLBHaITVM_8pT3SzURMbA.png" /><figcaption>Red zone where alpha = 1</figcaption></figure><p>We need to detect whether a pixel in the red opaque zone belongs to the icon or not.</p><p>I can suggest using an additional RGB color as a marker. The only requirement is that it must be a unique color for the container and its children to which we are applying the AGSL effect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nubnETXkwfYHQlIEk0XQCw.png" /><figcaption>Add markerColor as float unifirm param for agsl shader.</figcaption></figure><p>Let’s use <strong>Cyan RGB</strong> as the marker color. Tint the icons with Color.Cyan and pass the same <strong>Cyan color</strong> as a parameter to the AGSL script.</p><p>And define this parameter in AGSL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yq17jZov8ZTSQEspwqJ73Q.png" /><figcaption>Add new parameter: rgbMarkerColor as uniform float3</figcaption></figure><p>The AGSL shader source follows the same structure as in the previous chapter, with the only difference being in the last else block where the alpha is 1 — representing the center red color on the test screen.</p><p>Inside the opaque section, check if the pixel’s RGB color equals markerColor. If true, it is a pixel of the icon — color it with any color you want. Setting alpha = 1 is redundant because we are already in the opaque else case.<br>Otherwise, if false, it is definitely not an icon pixel — make it fully transparent by setting the RGB to black and alpha = 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HT2R2H2yKApfzo3EII58bA.png" /><figcaption>Use marker color to detect wether pixel belongs to Icon</figcaption></figure><p>The full AGSL script:</p><pre>@Language(&quot;AGSL&quot;)<br>const val ShaderSource_outlined_marker_color = &quot;&quot;&quot;<br>    uniform shader composable;<br>    <br>    uniform float cutoff_min; // Minimum cutoff value for transparency<br>    uniform float border_thickness; // Thickness of the border<br>    uniform float3 rgbColor;  // RGB color passed as parameter<br>    <br>    uniform float3 rgbMarkerColor;  // marker for Icon tint color<br>    <br>     // Constant for black (zero) RGB color<br>    const half3 BLACK_MASK_RGB = half3(0.0, 0.0, 0.0);<br>    <br>    half4 main(float2 fragCoord) {<br>        half4 color = composable.eval(fragCoord);<br>        <br>        // Calculate cutoff_max dynamically using border_thickness<br>        float cutoff_max = cutoff_min + border_thickness;<br><br>        // If alpha is exactly 0.0 (fully transparent), do nothing<br>        if (color.a == 0.0) {<br>            // Do nothing<br>        }<br>        // If alpha is below the minimum cutoff,<br>        // make it fully transparent and black<br>        else if (color.a &lt; cutoff_min) {<br>            color.rgb = BLACK_MASK_RGB; // Set to black<br>            color.a = 0.0; // Fully transparent<br>        } <br>        // If alpha is within the cutoff range (border area), <br>        // make it the custom color<br>        else if (cutoff_min &lt;= color.a &amp;&amp; color.a &lt;= cutoff_max) {<br>            color.rgb = rgbColor; // Set to custom color<br>            color.a = 1.0; // Fully opaque<br>        } <br>        // If alpha is above the maximum cutoff but less than <br>        //  fully opaque (outer area), make it fully transparent and black<br>        else if (cutoff_max &lt; color.a &amp;&amp; color.a &lt; 1.0) {<br>            color.rgb = BLACK_MASK_RGB; // Set to black<br>            color.a = 0.0; // Fully transparent<br>        } else {<br>         // Fully opaque case where alpha = 1<br>             if(color.rgb == rgbMarkerColor){<br>             //Icon area<br>                color.rgb = rgbColor;  // Set to Icon color<br>             }else{<br>             //pixel is out of icon shape - make it transparent<br>                color.rgb = BLACK_MASK_RGB;<br>                color.a = 0.0;<br>            }<br>        }<br><br>        return color;<br>    }<br>&quot;&quot;&quot;</pre><p>And here’s the solution demo for three cases:</p><ul><li>When the central part has an opaque border in the center in both the collapsed and expanded states (<strong>blurRadius = 16dp</strong>).</li><li>When in the expanded state, only the icon shapes are opaque, but in the collapsed state, there is still an opaque border (<strong>blurRadius = 26dp</strong>).</li><li>The case when the blur radius is large enough that there is no opaque border in either the expanded or collapsed states (<strong>blurRadius = 36dp</strong>).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*f-mqRDLEVi_iUsCEjl8J1A.gif" /><figcaption>blurRadius 16.dp</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*ucu3DGrhCrb2cuKJTe3_vQ.gif" /><figcaption>blurRadius 26.dp</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*lh0kitLN7mLi99BdNvu5mA.gif" /><figcaption>blurRadius 26.dp</figcaption></figure><p>Note that despite all the examples being executed with borderAlphaThickness = 0.05f, increasing the blurRadius also increases the thickness of the border.</p><h4>Pros and Cons of the Current Solution</h4><h4>Pros:</h4><ul><li>The implementation of AGSL is relatively straightforward and satisfies the requirements outlined at the beginning of the article.</li><li>The overlapping is handled automatically, so there’s no need to manually hide underlying icons when collapsed.</li><li>Should also work with a larger number of metaballs.</li><li>Works fine with different blur radiuses.</li></ul><h4>Cons:</h4><ul><li>The additional marker color parameter can become a potential source of bugs if it is passed but not properly set as the tint color.</li><li>It’s necessary to ensure that the marker color has a unique RGB value and is distinct from the color used for the blur effect.</li><li>The disappearing overlapping icon acts like an invisible transparent layer. While this is fine for Material 3 (which is more abstract), it might break the design concept for old-school adherents of Material Design 2.</li></ul><h3>Advansed AGSL: Filtering Areas by Alpha Value, Marker Color and Calculated Brightness.</h3><p>Solution from the previous chapter with greater duration and slightly zoomed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*k3nkqjSeE-Z9tutJNYcRGg.gif" /><figcaption>Icon disappears abruptly (not smooth)</figcaption></figure><p>The left icon disappears abruptly under the sharp, invisible border. Let’s fix this by making it fade out smoothly as it approaches and become completely invisible in the collapsed state.</p><p>Based on the previous chapter, where the else case (in this case, alpha = 1) checks for equality with the colorMarker value, I will make a modification by adding an additional check for equality with the Black RGB value and leave the else case empty:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hW55iNq39TUn2BJZg-fcsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*cN0p-qw9Nsm6224Ph7wtaQ.gif" /><figcaption>left icon gets overlapped by the blur area during the expanding/collapsing</figcaption></figure><p>During collapsing, we see the color of the left (behind) icon, which is partially overlapped by the top metaball shape, as being close to rgbMarkerColor (Color.CYAN). However, it&#39;s slightly different, so the condition color.rgb == rgbMarkerColor does not match. As the icons get closer, this &quot;almost markerColor&quot; gradually transitions to almost black (the metaball circular button background color used for blurring).</p><p>The reason why the color is not exactly Cyan is due to the blending effect. As the left icon becomes overlapped by the blurred layer of the right metaball, the marker color is distorted. Depending on the transparency of the black blurred color above the marker color, we see either a color very close to the marker or one closer to black.</p><p>From the video, we can observe a smooth transition from one color to another.</p><p>To maximize the effect of brightness change, let’s use a MarkerColor with the highest possible brightness — pure white color (1, 1, 1). The final color is determined by the circle button background used for blurring, which is black in our case—perfectly suitable for the next solution.</p><p><strong>Change </strong><strong>MarkerColor to White:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*hlfNRuBhjq8rnh0CADk8ng.gif" /><figcaption>Opaque almost White to opaque almost Black transition.</figcaption></figure><p>In the final GIF, with markerColor = (1, 1, 1) (White), we can see that the left icon, during overlapping with the right metaball as they move closer, transitions from fully opaque with an RGB value close to white to fully opaque with an RGB value close to black.</p><p><strong>The solution in this chapter involves using a brightness change from bright to dark and converting those changes into a transparency change from opaque to transparent.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8CPstoAxFyCZYYsCnISZAw.png" /><figcaption>Use brightness as alpha</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*x_0aiGzvUnQfN71wBPJc3A.gif" /><figcaption>Brightness as alpha (Blur radus 16.dp)</figcaption></figure><p>This works fine in the case where the blur radius is so small that the metaballs have an opaque circular shape (ed area I mentioned in the first chapter <strong>AGSL: Investigating Color Test</strong>) in the center (the case with a radius of 16.dp). However, when using a larger radius where, in the collapsed state, only the opaque pixels belonging to the icon remain without a border. However, when using a larger radius where, in the collapsed state, only the opaque pixels belonging to the icon remain without a border, a UI issue arises.<br>Let’s test it with a blur value greater than 36.dp:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*PSbFrsDXlC3JmyaWZcMaFA.gif" /><figcaption>Brightness as alpha (Blur radus 45.dp)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*APS4Fdja9DbZlsZNcx5SoA.png" /><figcaption><strong>Issue</strong>: the back-layer trash icon is visible.</figcaption></figure><p>Let’s create a helper function named adjustAlpha to dynamically adjust the alpha channel. This function takes the current alpha value as input and performs two key operations:</p><ol><li><strong>Exponentiation</strong>: It raises the alpha value to the 4th power. This operation helps to smooth out transitions by emphasizing higher values while reducing smaller ones more rapidly.</li><li><strong>Thresholding</strong>: After exponentiation, it checks if the adjusted alpha is less than a predefined threshold (e.g., 0.01). If it is, the function returns 0.0 (fully transparent); otherwise, it returns the adjusted alpha value.</li></ol><p>This combination of operations ensures that even small alpha values fade out smoothly to full transparency without abrupt visual glitches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s9nU3I1tSSW79jxUCTl9Uw.png" /><figcaption>adjust alpha value</figcaption></figure><p>By using this helper function, I can easily handle alpha transitions in a smooth way.<br>Additionally, when the adjusted transparency is 0, we set the RGB value to the mask color (e.g., black). If it is not 0, the function assigns the rgbColor. In the current example, the rgbColor is also black, but if we use a different color for blurring, this logic ensures proper handling of the transparency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M6Xf-RuXN8kctauNGGavuw.png" /><figcaption>Usage of ajustAlpha() helper function.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*2hy494VgjfI7aXgp0Wcr-g.gif" /><figcaption>Final solution. Blur radius 36.dp</figcaption></figure><p>Full AGSL script:</p><pre>@Language(&quot;AGSL&quot;)<br>const val ShaderSource_outlined_marker_color_and_marker_brightness = &quot;&quot;&quot;<br>    uniform shader composable;<br>    <br>    uniform float cutoff_min; // Minimum cutoff value for transparency<br>    uniform float border_thickness; // Thickness of the border<br>    uniform float3 rgbColor;  // RGB color passed as a parameter<br>    uniform float3 rgbMarkerColor;  // Marker for Icon tint color<br>    <br>    // Constant for black (zero) RGB color<br>    const half3 BLACK_MASK_RGB = half3(0.0, 0.0, 0.0);<br><br>    // Helper function to adjust alpha dynamically<br>    float adjustAlpha(float alpha) {<br>        // Define the threshold value<br>        const float threshold = 0.01;<br>    <br>        // Calculate the alpha raised to the power of 4<br>        float adjustedAlpha = pow(alpha, 4.0);<br>    <br>        // Return either the adjusted alpha or 0 if below the threshold<br>        return adjustedAlpha &lt; threshold ? 0.0 : adjustedAlpha;<br>    }<br>    <br>    half4 main(float2 fragCoord) {<br>        half4 color = composable.eval(fragCoord);<br>        <br>        // Calculate cutoff_max dynamically using border_thickness<br>        float cutoff_max = cutoff_min + border_thickness;<br><br>        // If alpha is exactly 0.0 (fully transparent), do nothing<br>        if (color.a == 0.0) {<br>            // Do nothing<br>        }<br>        // If alpha is below the minimum cutoff, make it fully transparent and black<br>        else if (color.a &lt; cutoff_min) {<br>            color.rgb = BLACK_MASK_RGB; // Set to black<br>            color.a = 0.0; // Fully transparent<br>        } <br>        // If alpha is within the cutoff range (border area), make it the custom color<br>        else if (cutoff_min &lt;= color.a &amp;&amp; color.a &lt;= cutoff_max) {<br>            color.rgb = rgbColor; // Set to custom color<br>            color.a = 1.0; // Fully opaque<br>        } <br>        // If alpha is above the maximum cutoff but less than fully opaque (outer area),<br>        // make it fully transparent and black<br>        else if (cutoff_max &lt; color.a &amp;&amp; color.a &lt; 1.0) {<br>            color.rgb = BLACK_MASK_RGB; // Set to black<br>            color.a = 0.0; // Fully transparent<br>        } <br>        // Fully opaque case where alpha = 1<br>        else {<br>            if (color.rgb == rgbMarkerColor) {<br>                // Icon area<br>                color.rgb = rgbColor; // Set to Icon color<br>            } else if (color.rgb == rgbColor) {<br>                // Some black inner metaball area could be opaque - make it transparent<br>                color.rgb = BLACK_MASK_RGB;<br>                color.a = 0.0;<br>            } else {<br>                // Compute current brightness<br>                float brightness = (color.r + color.g + color.b) / 3.0;<br>                float adjustedBrightness = adjustAlpha(brightness);<br><br>                // Set brightness as the alpha channel<br>                color.a = adjustedBrightness;<br><br>                // Set RGB color based on adjusted brightness<br>                if (adjustedBrightness == 0) {<br>                    color.rgb = BLACK_MASK_RGB; // Fully transparent<br>                } else {<br>                    color.rgb = rgbColor; // Custom color<br>                }<br>            }<br>        }<br><br>        return color;<br>    }<br>&quot;&quot;&quot;</pre><h4>Pros</h4><ul><li>Looks greate. Works in accordance with UI requirements, ensuring the smooth Icon disappearing as the metaball Buttons move closer together.</li></ul><h4>Cons</h4><ul><li><strong>Complex Logic</strong>: The implementation introduces more complexity, particularly in handling brightness-to-transparency calculations, which may increase the likelihood of bugs.</li><li><strong>Blur Radius Limitation</strong>: Very large blur radius values require fine-tuning the transparency calculation by brightness (AGSL: adjustAlpha()) to maintain expected behavior.</li><li><strong>Scalability Issues</strong>: When working with more than two metaball elements, additional adjustments to the transparency calculation function may be needed.</li><li><strong>Marker and Blur Color Restrictions</strong>: The marker color must be strictly white, while the blur color must be strictly black to avoid blending inconsistencies.</li><li><strong>Design Dependencies</strong>: All required colors, including the icon color, border color, and transparency of the inner zone, must be explicitly set through the AGSL shader, increasing reliance on shader logic.</li></ul><p><a href="https://github.com/yuriyskulskiy/android-compose-playground/blob/main/app/src/main/java/com/skul/yuriy/composeplayground/feature/gooey/blurConcept/ExampleRuntimeRenderEffectOutline.kt"><strong>Github link for current composable section</strong></a><strong> and </strong><a href="https://github.com/yuriyskulskiy/android-compose-playground/blob/main/app/src/main/java/com/skul/yuriy/composeplayground/feature/gooey/blurConcept/util/shader/OutlineAgslShader.kt"><strong>link to the AGSL shaders</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb8b0e72286c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chaining Blur and AGSL Runtime RenderEffects to Create Transparent Metaball Backgrounds with…]]></title>
            <link>https://medium.com/@yuriyskul/chaining-blur-and-agsl-runtime-rendereffects-to-create-transparent-metaball-backgrounds-with-15680ad1e1a9?source=rss-eaf677d34c58------2</link>
            <guid isPermaLink="false">https://medium.com/p/15680ad1e1a9</guid>
            <dc:creator><![CDATA[Yuriy Skul]]></dc:creator>
            <pubDate>Thu, 28 Nov 2024 15:47:11 GMT</pubDate>
            <atom:updated>2024-12-01T21:15:14.165Z</atom:updated>
            <content:encoded><![CDATA[<h3>Chaining Blur and AGSL Runtime RenderEffects to Create Transparent Metaball Backgrounds with Outline Stroke Borders in Jetpack Compose.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*Ti6gkpZYA132IxxCssUsuA.gif" /></figure><p>This is the third part of our journey into creating metaball backgrounds in Jetpack Compose. In this section, we focus on enhancing the design by adding <strong>outline stroke borders</strong> to transparent metaballs. This article explores how to achieve this effect by <strong>chaining a Blur RenderEffect with an AGSL Runtime RenderEffect.</strong></p><p><a href="https://medium.com/@yuriyskul/building-a-metaballs-gooey-animation-in-android-compose-using-rendereffect-api-120b8f8465da"><strong>Part 1</strong>: Creating a simple metaball background using a <strong>chain of BlurMask and ColorMaskFilter</strong>.</a></p><p><strong>Part 2</strong>:<a href="https://medium.com/@yuriyskul/metaballs-in-jetpack-compose-classic-math-approach-using-field-function-1-distance%C2%B2-37f86738db30"> Simplified metaball concept by introducing the <strong>mathematical definition of metaballs</strong> and exploring the metaball function.</a></p><p>The limitation of <strong>Part 1</strong> approach lies in the way the ColorFilter operates. It only allows linear transformations of the alpha channel, which restricts its flexibility. For example, it is not possible to make pixels fully transparent if their alpha is below a certain threshold, turn pixels fully opaque if their alpha is within a specific range, and then make them transparent again if their alpha exceeds a maximum limit. This limitation makes the ColorFilter less suitable for advanced metaball effects that require dynamic transparency control.</p><p><strong>Part 2</strong>: This part is implemented directly on the Canvas using the metaball math field function (no blur required), which places a significant load on the CPU. To simplify the implementation, a 100x100 grid was used to simulate pixels. While it is technically possible to achieve the goal of this article with this approach, I would first prefer to move the mathematical concept to an API level that leverages the GPU directly. This transition would provide a foundation for exploring more advanced solutions in the future without causing lags or screen freezes.</p><p>Based on the approach in the <strong>Part 1</strong> article, which uses a chain of render effects, let’s try replacing the linear ColorFilter with a <strong>runtime render effect</strong> created from an <strong>AGSL render script</strong>. This runtime render effect will filter (override the color and transparency of a pixel) based on the transparency level of the pixel after it has been blurred.</p><pre>@RequiresApi(Build.VERSION_CODES.TIRAMISU)<br>val metaBallAGSLRenderEffect = RenderEffect.createChainEffect(<br>    RenderEffect.createRuntimeShaderEffect(<br>        RuntimeShader(AgslShaderSource), <br>        &quot;composable&quot;    // Specify the input name<br>    ),<br>    RenderEffect.createBlurEffect(100f, 100f, Shader.TileMode.MIRROR), // Add blur effect,<br><br>).asComposeRenderEffect()</pre><p>And usage is any midifier’s graphics layer like:</p><pre>Canvas(<br>            modifier = Modifier<br>                .fillMaxSize()<br>                .graphicsLayer {<br>                    this.renderEffect = metaBallAGSLRenderEffect<br>                }<br>        ) {<br>         //content<br>        }</pre><p>If needed, we can apply it in a split manner or even move the AGSL render effect up to the parent composable, but the order should remain as follows:</p><pre>...<br>    modifier = Modifier<br>         ...<br>        .graphicsLayer {<br>            renderEffect = agslComposableRenderEffect<br>        }<br>         ...<br>        .graphicsLayer {<br>            renderEffect = blurComposableRenderEffect<br>        }<br><br>...</pre><p>And the AGSL render scripts:</p><p>For example this simple test script :</p><pre>@Language(&quot;AGSL&quot;)<br>const val AgslShaderSourceSimple = &quot;&quot;&quot;<br>    uniform shader composable;<br>    const float CUTOFF = 0.5; <br>    <br>    half4 main(float2 fragCoord) {<br>        half4 color = composable.eval(fragCoord);<br>        color.a = step(CUTOFF, color.a);<br>        return color;<br>    }<br>&quot;&quot;&quot;</pre><p>On top of Color.White background will produce next:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*sD-tojKC4yUbIuVHu-9D2A.gif" /><figcaption>Simple metaball test on top of white</figcaption></figure><p>step is a function that outputs either 0.0 or 1.0 based on whether x is below or above the edge value.</p><pre>step(edge, x) = 0.0 if x &lt; edge<br>                1.0 if x &gt;= edge</pre><p>To fix the unexpected dark side effect at the contour of the metaball shape, let’s set a specific color, such as black, for every inner pixel of the metaball. This is because the step function causes all pixels inside the metaball to become fully opaque (alpha = 1), while pixels outside remain transparent:</p><pre>@Language(&quot;AGSL&quot;)<br>const val AgslShaderSourceSimpleSolidBlack = &quot;&quot;&quot;<br>    uniform shader composable;<br>    const float CUTOFF = 0.5; <br>    const float3 RGB_BLACK = float3(0.0, 0.0, 0.0); // constant  Black rgb<br><br>    half4 main(float2 fragCoord) {<br>        half4 color = composable.eval(fragCoord);<br>        color.a = step(CUTOFF, color.a);<br>        if (color.a == 1) {<br>            color.rgb = RGB_BLACK;<br>        }<br>        return color;<br>    }<br>&quot;&quot;&quot;</pre><p>Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*NlpNvoNzAm6YPI6KWcQFqQ.gif" /><figcaption>Simple solid metaball test on top of white</figcaption></figure><p>The step() function, like the color matrix, can only split the result at a single value. However, for an outline border shape, we need to use a threshold with both a minimum alpha value and a maximum alpha value. Everything outside this threshold should be made completely transparent, while every pixel with an alpha matching this range should be assigned a fully opaque color.</p><p>Therefore, instead of using the step() function, we manually handle three cases to achieve the desired outline border effect:</p><ul><li><strong>Case 1</strong>: If the pixel’s alpha value is less than the minimum cutoff threshold, the pixel is outside the metaball. In this case, we make the pixel fully transparent by setting its alpha to 0.</li><li><strong>Case 2</strong>: If the pixel’s alpha value is within the range defined by the minimum and maximum cutoff thresholds, it is part of the outline border. Here, we assign the pixel any RGB color we want (e.g., the border color) and make it fully opaque by setting its alpha to 1.</li><li><strong>Case 3</strong>: If the pixel’s alpha value is greater than the maximum cutoff threshold, the pixel should again be made fully transparent.</li></ul><p><strong>Case 1</strong> and <strong>Case 3</strong> handle pixels outside the alpha threshold range the same way by making them fully transparent, so they can be combined into a single branch.</p><pre>@Language(&quot;AGSL&quot;)<br>const val AgslOutlineBorderShaderSourceDraft = &quot;&quot;&quot;<br>    uniform shader composable;<br><br>    // Constants for colors<br>    const float3 WHITE_BORDER_COLOR = float3(1.0, 1.0, 1.0);     <br>    const float CUTOFF = 0.5; // Define a constant cutoff value<br>    const float BORDER_THICKNESS = 0.05; // Border thickness<br><br>    half4 main(float2 fragCoord) {<br>        half4 color = composable.eval(fragCoord);<br><br>        if (color.a &lt; CUTOFF || color.a &gt; (CUTOFF + BORDER_THICKNESS)) {<br>            // Pixel is outside the border range, make it fully transparent<br>            color.a = 0.0;<br>        } else {<br>            // Pixel is in the border range, assign border color and make it opaque<br>            color.rgb = WHITE_BORDER_COLOR;<br>            color.a = 1.0;<br>        }<br><br>        return color;<br>    }<br>&quot;&quot;&quot;</pre><p>But the result is not like expected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*AVC1YBYwU2bwefehUBS_jQ.gif" /><figcaption>Draft outline border AGSL</figcaption></figure><p>However to properly eliminate the non-transparent white background, simply setting alpha = 0 is not enough. This is because the color values (rgb) can still affect the result of compositing or effects like blur.<br>To properly eliminate the non-transparent white background, simply setting alpha = 0 is not enough. This is because the color values (rgb) can still affect the result of compositing or effects like blur. For example, when you set color.a = 0.0 with a black color (float3(0.0, 0.0, 0.0)), the pixel becomes fully transparent. Since black does not add any brightness, it does not influence the background, even if small blending errors occur due to transparency.<br>However, with other colors (e.g., float3(1.0, 0.0, 0.0)), even with color.a = 0.0, the pixel color can still blend with the background due to interpolation or compositing errors. This is especially noticeable when applying effects like blur, which can smear the rgb values, even if the alpha is zero. Therefore, in such cases, a fully transparent black background is used to prevent any visual artifacts.</p><p>Here’s the solution of a final AGSL render script for achieving the metaball effect with an opaque border and a fully transparent metaball inside for blurred circle shapes:</p><pre>@Language(&quot;AGSL&quot;)<br>const val AgslOutlineBorderShaderSource = &quot;&quot;&quot;<br>    uniform shader composable;<br><br>    // Constants for colors<br>    const float3 WHITE_BORDER_COLOR = float3(1.0, 1.0, 1.0);     <br>    const float3 BLACK_MASK_COLOR = float3(0.0, 0.0, 0.0); <br>    <br>    const float CUTOFF = 0.5; // Define a constant cutoff value<br>    const float BORDER_THICKNESS = 0.05; // Border thickness<br><br>    half4 main(float2 fragCoord) {<br>        half4 color = composable.eval(fragCoord);<br><br>        if (color.a &lt; CUTOFF || color.a &gt; (CUTOFF + BORDER_THICKNESS)) {<br>            //  Pixel is outside the border range, make it fully transparent<br>            color.rgb = BLACK_MASK_COLOR;<br>            color.a = 0.0;<br>        } else {<br>            // Pixel is in the border range, assign border color and make it opaque<br>            color.rgb = WHITE_BORDER_COLOR;<br>            color.a = 1.0;<br>        }<br><br>        return color;<br>    }<br>&quot;&quot;&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*j4l4xcK443SzF96ANnD0Mw.gif" /><figcaption>Final solution</figcaption></figure><p><a href="https://github.com/yuriyskulskiy/android-compose-playground/tree/main/app/src/main/java/com/skul/yuriy/composeplayground/feature/metaballBlur"><strong>Source code Github link</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15680ad1e1a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack Compose: Gooey (Metaball) Interaction Using AGSL Shader and Blur — Fixing Coloring Issues]]></title>
            <link>https://medium.com/@yuriyskul/jetpack-compose-gooey-metaball-interaction-using-agsl-shader-and-blur-fixing-coloring-issues-c70affdcde0f?source=rss-eaf677d34c58------2</link>
            <guid isPermaLink="false">https://medium.com/p/c70affdcde0f</guid>
            <dc:creator><![CDATA[Yuriy Skul]]></dc:creator>
            <pubDate>Mon, 25 Nov 2024 02:31:12 GMT</pubDate>
            <atom:updated>2024-11-25T02:31:12.197Z</atom:updated>
            <content:encoded><![CDATA[<h3>Jetpack Compose: Gooey (Metaball) Interaction Using AGSL Shader and Blur — Fixing Coloring Issues</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*TelNWEW4A5OYLR3ZjQTLmQ.gif" /><figcaption>Proper AGSL shader that resolves the dark color issue</figcaption></figure><ul><li><a href="https://medium.com/@yuriyskul/gooey-metaball-effects-on-android-with-jetpack-compose-blurring-and-alpha-filtering-concepts-63f1cf879257">Part 1: Gooey (Metaball) Effects on Android with Jetpack Compose: Blurring and Alpha Filtering Concepts Across All API Levels</a></li><li><a href="https://medium.com/@yuriyskul/compose-gooey-metaball-button-effect-fixing-blur-mask-issues-on-pre-android-10-devices-with-d8f3fadc2680">Part 2: Compose Gooey (Metaball) Button Effect: Fixing Blur Mask Issues on Pre-Android 10 Devices with Gradient Halo and Icon Simplification</a></li></ul><blockquote>This article is an addition to the previous series, focusing on solving the problem of correct color rendering in AGSL shaders. We explore advanced rendering scripts in Jetpack Compose to ensure accurate color application and address common issues with shader behavior.</blockquote><p>Rendering a gooey effect with a blur halo and applying an AGSL runtime render effect was demonstrated in the previous article as the first example among several similar approaches. Now, let’s change the color from black to another, such as red, and examine the result from the previous article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*mOCLGKRL6vJFTkjIaOQVxw.gif" /><figcaption>Color issue in AGSL metaball section</figcaption></figure><p>This side effect is related to the specifics of how the shader processes colors. The darkening effect was not noticeable when using black with the basic AGSL script:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BR5rbTWmXWqxsOjRN7y4tQ.png" /><figcaption>Simple AGSL script from the first part</figcaption></figure><p>Obviously, the resulting color inside the circle is not what we need. The line color.a = step(transparencyLimit, color.a) assigns the pixel&#39;s transparency to either 0 or fully opaque. Naturally, the first idea is to try assigning the desired color when the pixel&#39;s transparency, after the step function, equals 1, as inside the circle we expect a fully opaque color:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NQotYxv6RpQ1T6qfNK7AYQ.png" /><figcaption>Wrong try: It makes everything red color inside circle</figcaption></figure><p>The result is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*89r90Z3z2Ru_nC3N8-ZgSA.png" /></figure><p>The white icon has disappeared because everything inside (every pixel) has turned red.</p><p>Let’s run a simple test shader:</p><pre>@Language(&quot;AGSL&quot;)<br>const val ShaderSource_coloring_test = &quot;&quot;&quot;<br>    uniform shader composable;<br>    <br>    uniform float transparencyLimit; // The alpha threshold for transparency logic<br>    <br>    half4 main(float2 fragCoord) {<br>        half4 color = composable.eval(fragCoord);<br><br>        // Debugging alpha ranges with distinct colors<br>        if (color.a == 0.0) {<br>            // Green for fully transparent pixels<br>            color.rgb = half3(0.0, 1.0, 0.0); <br>        } else if (color.a == 1.0) {<br>            // Red for fully opaque pixels<br>            color.rgb = half3(1.0, 0.0, 0.0); <br>        } else {<br>            // Case for semi-transparent pixels<br>            if (color.a &gt; transparencyLimit) {<br>                // Blue for semi-transparent pixels above the transparency limit (cutoff)<br>                color.rgb = half3(0.0, 0.0, 1.0); <br>            } else {<br>                // Pink for semi-transparent pixels below the transparency limit<br>                color.rgb = half3(1.0, 0.0, 1.0); <br>            }<br>        }<br><br>        // Set alpha to 1.0 to ensure all pixels are visible for debugging<br>        color.a = 1.0;<br><br>        return color;<br>    }<br>&quot;&quot;&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*2A6WKMBMSJLHON_hupAFBA.png" /></figure><ul><li>Green indicates areas with fully transparent pixels.</li><li>Red represents fully opaque pixels, such as the icon tint area.</li><li>Pink shows the semi-transparent area where alpha is less than the cutoff (transparency limit) and should be replaced with 0 transparency.</li><li>Blue highlights the problematic zone where the alpha value falls between the transparency limit and 1.</li></ul><p>I propose using this alpha range to replace the color with red (or any desired color) before applying the step function. This approach ensures that the icon retains its original color and alpha while removing the unwanted darkening side effect.</p><pre>if (transparencyLimit &lt; color.a &amp;&amp; color.a &lt; 1.0) {<br>   color.rgb = half3(rgbColor[0], rgbColor[1], rgbColor[2]);<br>}<br>//then apply step function for alpha channel</pre><p>Since everything below the transparency limit value will be made fully transparent, the check (transparencyLimit &lt; color) is unnecessary.</p><pre>if (color.a &lt; 1.0) {<br>   color.rgb = half3(rgbColor[0], rgbColor[1], rgbColor[2]);<br>}</pre><p>And the whole AGSL script:</p><pre>@Language(&quot;AGSL&quot;)<br>const val ShaderSourceProperColoring = &quot;&quot;&quot;<br>    uniform shader composable;<br>    <br>    uniform float transparencyLimit;<br>    uniform float3 rgbColor;<br>    <br>    half4 main(float2 fragCoord) {<br>        half4 color = composable.eval(fragCoord);<br>        <br>        if (color.a &lt; 1) {<br>            color.rgb = half3(rgbColor[0], rgbColor[1], rgbColor[2]); <br>        }<br>        color.a = step(transparencyLimit, color.a);<br>        return color;<br>    }<br>&quot;&quot;&quot;</pre><p>Let’s copy and paste the AGSL section (the top screen from the previous articles) to the bottom of the screen column. Then, we’ll add some radio buttons to switch between the simple and new advanced AGSL scripts and set Red as the color instead of Black:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*K7FLcOfuuVMBXFSvMDqP0g.gif" /><figcaption>new AGSL script result</figcaption></figure><p>Something is wrong: when the advanced AGSL script render effect is active, it colors almost the entire screen above but leaves the bottom description and divider intact. Why?</p><p>For explanation purposes, I will temporarily place our new section in the second-to-last position on the screen list and hardcode the test AGSL script that I used earlier for debugging:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*oylw-QAQCNumZ-WafevAoA.png" /></figure><p>The render effect with AGSL is not limited to the bounds of the composable content within the section. Instead, it is applied to the entire graphics layer, which is why the whole screen column was colored green.</p><p>The reason everything below the current section remains unaffected is due to the order of application. The render effect was applied after the upper sections but before the lower ones, meaning the lower sections and text were drawn after the effect had completed. As for the top bar, I assume it is rendered on a separate graphics layer or it is drawn after the render effect is applied to the column, it will “cover” the shader effect visually, making it seem unaffected.</p><p>Important: To avoid such unexpected side effects, always use clipping within graphics layers to ensure the effect is confined to the desired bounds.</p><pre>Box(<br>            modifier = modifier<br>                .graphicsLayer {<br>                    clip = true<br>//                        ...<br>//                    apply runtime render effect<br>                }<br>//                ...</pre><p>And the whole container with this runtime render effect:</p><pre>enum class ShaderType(val source: String) {<br>    Simple(ShaderSourceSimple),<br>    FixColor(ShaderSourceProperColoring),<br>}</pre><pre>@Composable<br>fun MetaballBoxWithShaders(<br>    modifier: Modifier = Modifier,<br>    shaderType: ShaderType = ShaderType.Simple, // Default to &quot;Simple&quot;<br>    transparencyLimit: Float = 0.5f,<br>    color: Color = Color.Black,<br>    content: @Composable BoxScope.() -&gt; Unit,<br>) {<br>    if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.TIRAMISU) {<br>        // Remember the shader based on the selected shader type<br>        val metaBallShader = remember(shaderType) {<br>            RuntimeShader(shaderType.source)<br>        }<br><br>        Box(<br>            modifier = modifier<br>                .graphicsLayer {<br>                    clip = true<br>                    metaBallShader.setFloatUniform(&quot;transparencyLimit&quot;, transparencyLimit)<br>                    metaBallShader.setFloatUniform(&quot;rgbColor&quot;, color.red, color.green, color.blue)<br>                    renderEffect = RenderEffect<br>                        .createRuntimeShaderEffect(metaBallShader, &quot;composable&quot;)<br>                        .asComposeRenderEffect()<br>                },<br>            content = content,<br>        )<br>    }<br>}</pre><p><a href="https://github.com/yuriyskulskiy/android-compose-playground/blob/main/app/src/main/java/com/skul/yuriy/composeplayground/feature/gooey/blurConcept/ExampleRuntimeRenderEffectColorFix.kt"><strong>Github link: ExampleRuntimeRenderEffectColorFix.kt</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c70affdcde0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>