<?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 Gaurav Gawali on Medium]]></title>
        <description><![CDATA[Stories by Gaurav Gawali on Medium]]></description>
        <link>https://medium.com/@gaurav.gawali?source=rss-a7e2f2503ca2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pqDBM3UwG6-9MGH2RQpSfA.png</url>
            <title>Stories by Gaurav Gawali on Medium</title>
            <link>https://medium.com/@gaurav.gawali?source=rss-a7e2f2503ca2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 10:48:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gaurav.gawali/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[How I Eliminated CameraX PreviewView Jank in Jetpack Compose Using a Snapshot Transition]]></title>
            <link>https://medium.com/eightinity/how-i-eliminated-camerax-previewview-jank-in-jetpack-compose-using-a-snapshot-transition-978f67236246?source=rss-a7e2f2503ca2------2</link>
            <guid isPermaLink="false">https://medium.com/p/978f67236246</guid>
            <category><![CDATA[jetpack-navigation]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Gaurav Gawali]]></dc:creator>
            <pubDate>Thu, 18 Jun 2026 12:11:15 GMT</pubDate>
            <atom:updated>2026-06-18T12:11:15.410Z</atom:updated>
            <content:encoded><![CDATA[<p>A deep dive into why CameraX PreviewView animations stutter inside Jetpack Compose, and how replacing the live preview with a bitmap snapshot eliminated jank during navigation transitions.</p><p>If you’ve ever seen a CameraX overlay get “<strong>stuck halfway</strong>” during a Compose navigation transition, this article explains why — and how a bitmap snapshot completely eliminated the jank.</p><p><em>~8 min read</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZAxIkACzFX5ZccOWtv-W-Q.png" /></figure><p>I tap the close button. The camera overlay should whoosh off to the right. The underlying screen should slide in from the left. Easy, right?</p><p>Instead it hangs. Half on screen. Half gone. Like someone paused a video mid-swipe and forgot to hit play again.</p><p>The fix wasn’t changing the animation. It was replacing the live CameraX preview with a frozen bitmap and delaying expensive recomposition until after the transition.</p><p>In hindsight, I wasn’t animating a composable at all. I was trying to animate a live rendering surface.</p><p>That was my camera overlay dismiss on Android, and it felt worse than a crash. Crashes are honest. This was a UI that <strong><em>almost</em></strong> worked, every single time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*T7pOkBHv2MkjmHo9tykPGw.gif" /></figure><p><strong>At a glance</strong></p><p>Three changes fixed the dismiss:</p><p>1. Capture previewView.bitmap, hide the live preview, unbind CameraX, then animate a static Image.</p><p>2. Defer network reloads and nav-arg clears until ~360 ms after close (320 ms slide + buffer).</p><p>3. Use linear easing on dismiss so a struggling animation doesn’t read as “<strong>stuck halfway</strong>.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QD-n3pKkwA7K1jkmK_1tmQ.png" /></figure><p><strong>What you need</strong></p><p>You should already be comfortable with Jetpack Compose, CameraX (PreviewView, ProcessCameraProvider), and Compose Navigation (AnimatedContent or similar slide transitions).</p><p><strong>Stack I tested</strong>: Android API 26+, CameraX 1.3.x, Compose BOM 2024.02+, Kotlin 1.9+.</p><p>The snapshot trick works on older CameraX versions that expose PreviewView.bitmap, but always verify on your target devices.</p><p><strong>Why SurfaceView doesn’t slide like normal UI</strong></p><p>Camera previews don’t behave like a Text composable. CameraX’s PreviewView renders into a SurfaceView or TextureView, and a SurfaceView in particular isn’t really part of your view hierarchy.</p><p>The View moves immediately, but the Surface layer is composed separately, so it can lag behind during animations. That’s why you often see flicker, black seams, or content trailing behind the UI transition.</p><p>Even with TextureView, you’re still asking the GPU to reposition a live camera stream every frame during a navigation animation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B-aObhOGvkkj_EQDb-NKoA.png" /></figure><p>CameraX’s own PreviewView documentation warns that transition animations involving SurfaceView and TextureView have limitations because they are rendered differently from normal Compose UI.</p><p><strong>Why AnimatedContent and AndroidView make it worse</strong></p><p>The overlay lived inside AnimatedContent with horizontal slide transitions. Compose expects draw-phase transforms on composables.</p><p>PreviewView inside AndroidView is different. It hosts a live camera surface with its own rendering pipeline, buffer lifecycle, and communication with the camera HAL.</p><p>That combination is what produced the dismiss jank.k</p><pre><br>@Composable<br>fun CameraOverlayNav(<br>    cameraRoute: CameraRoute?,<br>    onDismiss: () -&gt; Unit,<br>) {<br>    AnimatedContent(<br>        targetState = cameraRoute,<br>        transitionSpec = {<br>            slideInHorizontally(<br>                initialOffsetX = { it },<br>                animationSpec = tween(320, easing = FastOutSlowInEasing)<br>            ) togetherWith slideOutHorizontally(<br>                targetOffsetX = { it },<br>                animationSpec = tween(320, easing = FastOutSlowInEasing)<br>            )<br>        },<br>        label = &quot;camera_overlay&quot;<br>    ) { route -&gt;<br>        when (route) {<br>            null -&gt; HomeScreen()<br>            else -&gt; CameraOverlayScreen(route = route, onDismiss = onDismiss)<br>        }<br>    }<br>}<br><br>@Composable<br>fun CameraPreview(<br>    modifier: Modifier = Modifier,<br>    onPreviewViewReady: (PreviewView) -&gt; Unit,<br>) {<br>    AndroidView(<br>        modifier = modifier.fillMaxSize(),<br>        factory = { context -&gt;<br>            PreviewView(context).also { previewView -&gt;<br>                previewView.implementationMode =<br>                    PreviewView.ImplementationMode.COMPATIBLE<br>                onPreviewViewReady(previewView)<br>            }<br>        },<br>        update = { /* bind Preview use case */ }<br>    )<br>}</pre><p>AnimatedContent keeps both the entering and exiting content alive during the transition.</p><p>That works perfectly for normal Compose UI, but it becomes expensive when one side is a live camera preview continuously producing frames.</p><p><strong>Expensive work during the dismiss animation</strong></p><p>The camera surface wasn’t the only problem.</p><p>My dismiss animation lasts 320 ms, but the underlying screen immediately started network reloads, list refreshes, and recomposition at exactly the same time.</p><p>Those operations competed for the same frame budget as the transition itself.</p><pre>// Before: reload fired the instant close was tapped<br>fun onCloseTapped() {<br>    viewModel.reloadHome()          // network + list diffing<br>    navController.popBackStack()    // AnimatedContent starts exit<br>}</pre><p>The animation wasn’t just fighting the camera surface.</p><p>It was also competing with my own data layer.</p><p>Once I delayed that work until after the transition settled, the dismiss immediately became much smoother.</p><p><strong>Prior art (and what’s missing)</strong></p><p>The snapshot pattern isn’t new. A CameraX Stack Overflow answer shows the core trick: capture `previewView.bitmap`, animate the bitmap instead of the live preview, and tear down the real camera underneath.</p><p>Google’s Surface documentation explains why `SurfaceView` animations are difficult in the first place, and Compose performance guidance recommends keeping animation work in the draw phase whenever possible.</p><p>The missing piece was combining these ideas into a complete CameraX overlay dismiss strategy for Jetpack Compose.</p><p>What I couldn’t find was a single end-to-end guide for dismissing a CameraX overlay inside Compose without visible jank.</p><p>That’s exactly what this implementation tries to solve.</p><p><strong>The fix: snapshot, defer, slide</strong></p><p>The solution wasn’t a new animation.</p><p>It was changing what was being animated.</p><p>Instead of sliding a live PreviewView, I capture its current frame as a bitmap, remove the live camera from the transition, and animate a normal Compose Image instead.</p><p>At the same time, expensive reload work is delayed until after the animation finishes, giving the transition the full frame budget.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rTF7Dac77riWaUnbD9nGrQ.png" /></figure><p>At a high level, the dismiss flow changed from animating a live camera surface to animating a static image while the camera shuts down in the background.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*js2K09lnnRkbnIx--KT8NQ.gif" /></figure><p>Snapshot transition after replacing the live<em> PreviewView </em>with a bitmap and deferring expensive work.</p><p><strong>Snapshot dismiss</strong></p><p>The first optimization is capturing the current camera frame before the transition begins.</p><p>Once the bitmap exists, the live camera preview can disappear immediately while Compose animates a normal image instead.</p><pre>suspend fun captureDismissSnapshot(<br>    previewView: PreviewView,<br>    cameraProvider: ProcessCameraProvider,<br>): ImageBitmap? {<br>    val bitmap = previewView.bitmap ?: return null<br><br>    previewView.visibility = View.INVISIBLE<br><br>    cameraProvider.unbindAll()<br><br>    return bitmap.asImageBitmap()<br>}</pre><p>This removes the expensive live surface from the animation.</p><p>From Compose’s perspective, it is now animating a simple `Image`, which is much cheaper than animating a continuously updating camera preview.</p><pre>withFrameNanos { }<br><br>startDismissTransition()</pre><p>The `withFrameNanos { }` call gives Compose one rendering frame to draw the snapshot before the transition starts.</p><p>Without this synchronization point, the animation can briefly begin on a blank surface before the bitmap appears.</p><p><strong>Defer the heavy stuff</strong></p><p>Capturing a bitmap solved only half the problem. The underlying screen was still triggering network requests, list updates, and recomposition the moment the camera closed.</p><p>Those operations competed with the exit animation for the same frame budget, causing visible stutter. The fix was simple: delay expensive work until the transition finishes.</p><pre>class OverlayDismissController {<br>    private var deferredUntil = 0L<br><br>    fun onCloseStarted() {<br>        deferredUntil = SystemClock.uptimeMillis() + 360<br>    }<br><br>    suspend fun awaitSettleWindow() {<br>        val remaining = deferredUntil - SystemClock.uptimeMillis()<br>        if (remaining &gt; 0) delay(remaining)<br>    }<br>}<br><br>viewModelScope.launch {<br>    dismissController.awaitSettleWindow()<br>    homeRepository.reload()<br>}</pre><p>The animation gets the frame budget first, and the data refresh happens after the transition completes.</p><p><strong>Don’t clear state mid-animation</strong></p><p>I also stopped clearing navigation arguments the moment the overlay closed. Doing so forced unnecessary recomposition while the exit animation was still running.</p><p>Instead, navigation state is cleared only after the settle window completes, keeping the UI stable throughout the transition.</p><pre>scope.launch {<br>    captureAndStartDismiss()<br><br>    dismissController.awaitSettleWindow()<br><br>    navController.currentBackStackEntry<br>        ?.savedStateHandle<br>        ?.remove&lt;String&gt;(&quot;cameraRoute&quot;)<br><br>    navController.popBackStack()<br>}</pre><p>Small state changes can interrupt animations. Delaying them until the transition completes avoids unnecessary recomposition.</p><p><strong>GPU-friendly sliding</strong></p><p>Once the live camera preview was replaced with a bitmap, the remaining optimization was keeping the animation entirely in the draw phase.</p><p>Instead of triggering layout or recomposition every frame, the snapshot is translated using graphicsLayer, allowing the GPU to handle the movement efficiently.</p><pre>@Composable<br>fun DismissSnapshot(<br>    snapshot: ImageBitmap,<br>    progress: Float,<br>) {<br>    Image(<br>        bitmap = snapshot,<br>        contentDescription = null,<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .graphicsLayer {<br>                translationX = size.width * progress<br>            }<br>    )<br>}</pre><p><strong>Linear easing on dismiss</strong></p><p>I originally used FastOutSlowInEasing for both opening and closing the overlay. On dismiss, however, the aggressive deceleration made every dropped frame feel like the animation was getting stuck.</p><p>Switching only the exit animation to LinearEasing produced a steadier motion that felt smoother, even when the device was busy.</p><pre>slideOutHorizontally(<br>    targetOffsetX = { it },<br>    animationSpec = tween(<br>        durationMillis = 320,<br>        easing = LinearEasing<br>    )<br>)</pre><p>Instrument it</p><p>Finally, I added timestamped logging around the dismiss sequence. It made it easy to verify that snapshot capture, camera teardown, animation start, and data reload happened in the expected order.</p><pre>private fun logCloseTrace(step: String) {<br>    Log.d(<br>        &quot;CameraDismiss&quot;,<br>        &quot;$step @ ${SystemClock.uptimeMillis()}&quot;<br>    )<br>}</pre><p>Measuring the sequence removed the guesswork and made performance regressions much easier to spot.</p><p><strong>Tradeoffs</strong></p><p>No optimization is free, and this approach comes with a few tradeoffs:</p><ul><li><strong>previewView.bitmap can occasionally return </strong><strong>null</strong>, so a fallback path is still necessary.</li><li><strong>Holding a full-screen bitmap briefly increases memory usage</strong>, although only for the duration of the exit animation.</li><li><strong>The snapshot may be one frame older than the live preview</strong>, but it’s generally imperceptible during a 320 ms transition.</li><li><strong>Data refresh is delayed by about 360 ms</strong>, prioritizing animation smoothness over immediate updates.</li></ul><p>For a full-screen camera overlay, these tradeoffs are usually well worth the improvement in perceived performance</p><p><strong>Results</strong></p><p>After shipping the snapshot transition, the difference was immediately noticeable.</p><p>Dismiss animations became consistently smooth across my test devices. Frame drops disappeared, camera teardown no longer blocked navigation, and the UI finally behaved the way users expect.</p><p>More importantly, the animation stopped fighting the camera pipeline. By replacing the live PreviewView with a static bitmap during the transition, Compose could animate a lightweight Image instead of a continuously updating camera surface.</p><p>The biggest lesson wasn’t how to make the camera preview animate faster — it was realizing that <strong>the best animation was not animating the live camera preview at all.</strong></p><p><em>Sometimes the smoothest animation isn’t about making expensive UI faster — it’s about stopping expensive UI from being animated in the first place</em></p><p><strong>Eightinity Engineering</strong><br>We share real-world AI and mobile engineering insights. Before you go:</p><p>👏 Show your support by <strong>clapping</strong> and <strong>following</strong> the <strong>author</strong><br>🧠 Discover more AI, OpenAI, and SAM model articles<br>📱 Explore iOS, Android, and UI engineering blogs<br>🚀 Learn how we build AI-powered products at Eightinity<br>🔔 Follow us: <a href="https://www.linkedin.com/company/eightinity-technologies"><strong>LinkedIn</strong></a> | <a href="https://x.com/8inityStudio"><strong>X (Twitter)</strong></a> | <a href="https://www.eightinity.in/"><strong>Website</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=978f67236246" width="1" height="1" alt=""><hr><p><a href="https://medium.com/eightinity/how-i-eliminated-camerax-previewview-jank-in-jetpack-compose-using-a-snapshot-transition-978f67236246">How I Eliminated CameraX PreviewView Jank in Jetpack Compose Using a Snapshot Transition</a> was originally published in <a href="https://medium.com/eightinity">Eightinity</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>