惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

TaoSecurity Blog
TaoSecurity Blog
博客园 - 司徒正美
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 【当耐特】
M
MIT News - Artificial intelligence
罗磊的独立博客
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Stack Overflow Blog
Stack Overflow Blog
The GitHub Blog
The GitHub Blog
Google DeepMind News
Google DeepMind News
Security Archives - TechRepublic
Security Archives - TechRepublic
宝玉的分享
宝玉的分享
N
News and Events Feed by Topic
The Hacker News
The Hacker News
Google DeepMind News
Google DeepMind News
C
CERT Recently Published Vulnerability Notes
F
Full Disclosure
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
S
Security @ Cisco Blogs
H
Hacker News: Front Page
L
LangChain Blog
Microsoft Security Blog
Microsoft Security Blog
Y
Y Combinator Blog
B
Blog RSS Feed
H
Heimdal Security Blog
Google Online Security Blog
Google Online Security Blog
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 三生石上(FineUI控件)
V2EX - 技术
V2EX - 技术
V
Vulnerabilities – Threatpost
Help Net Security
Help Net Security
Hacker News - Newest:
Hacker News - Newest: "LLM"
T
Tailwind CSS Blog
W
WeLiveSecurity
T
Tenable Blog
D
DataBreaches.Net
Martin Fowler
Martin Fowler
Cyberwarzone
Cyberwarzone
Cisco Talos Blog
Cisco Talos Blog
S
Secure Thoughts
O
OpenAI News
L
LINUX DO - 热门话题
Vercel News
Vercel News
阮一峰的网络日志
阮一峰的网络日志
Jina AI
Jina AI
J
Java Code Geeks
Know Your Adversary
Know Your Adversary
IT之家
IT之家
Latest news
Latest news
Cloudbric
Cloudbric

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
I Couldn't Find a Rolling Text Library for Compose, So I Built One
morozione · 2026-05-12 · via DEV Community

A small library, a long journey through Compose animations, and a few bad ideas along the way.


The Itch

I work on a crypto-banking app. Crypto prices change every second, and a number that just snaps to a new value looks cheap. I wanted that satisfying "odometer" feeling — when a digit rolls through every value on the way to the next one. Like a slot machine, or like the kilometer counter in an old car.

So I went looking for a library.

What I Couldn't Find

There are several "animated number" libraries for Compose. The popular ones use AnimatedContent to flip between two digits — the old digit fades or slides out, the new one slides in. It looks fine, but it skips everything in between.

That's not what I wanted. I wanted 2 → 3 → 4 → 5, every digit visible on the way. If you change from 2 to 7, you should see 3, 4, 5, 6 pass by.

I searched, I asked around, I checked posts in different languages through Google Translate. Nothing did exactly this. So I started building.

The result is compose-rolling-text. Here's how I got there — including the dead ends.


Attempt #1: The Naive Column

My first idea was the obvious one: for each digit slot, render a vertical Column of digits (0..9), and scroll through it. Like an iOS picker.

It worked. Kind of. But:

  • It was laggy. Each digit slot was a tall column of 10 children. With 6 or 7 digits on screen, every animation frame triggered a heavy layout pass.
  • Centering was weird. During the scroll, the text baseline shifted by tiny amounts. Numbers looked like they were jumping by half a pixel.
  • Low-end devices suffered. Scrolling several of these widgets at once dropped frames. I needed something lighter.

Attempt #2: One Long String (The "Drum")

The breakthrough was simple: forget composables for each digit. Use one multi-line string.

If I'm going from 2 to 5, I build this string:

5
4
3
2

Enter fullscreen mode Exit fullscreen mode

Then I put it inside a Box that's only one line tall, with clipToBounds(). I start the string positioned so 2 is visible, and slide it up until 5 is visible. Done.

One Text composable, one animation, no fighting with layout.

This is what buildDrumText does, and I'll show it in a moment.


The graphicsLayer Trick

Now, how do you slide the string up?

My first try was to animate a Modifier.offset or padding. Two problems:

  1. Every animation frame caused a layout pass. Compose had to remeasure things on every frame.
  2. Centering broke during the animation. The container shifted, the parent's alignment recalculated, and digits drifted left or right by a pixel or two. The fix was Modifier.graphicsLayer:
BasicText(
    text = drumText,
    style = internalStyle,
    overflow = TextOverflow.Visible,
    maxLines = Int.MAX_VALUE,
    modifier = Modifier.graphicsLayer {
        translationY = verticalOffset
    }
)

Enter fullscreen mode Exit fullscreen mode

graphicsLayer applies the translation at the drawing stage, on the GPU. No layout pass, no remeasure. The text composable thinks it's still in the same place — only its pixels move. Smooth as butter, and centering stays rock-solid.

This was the moment everything clicked.


Easing: From Robot to Smooth

A linear animation feels mechanical — like a robot. Real-world objects don't move at constant speed; they speed up and slow down.

Material Design has a curve called "emphasized easing" that gives a natural settling effect: fast at the start, gentle at the end. I copied its values:

private val RollingEasing = CubicBezierEasing(0.2f, 0.0f, 0.0f, 1.0f)

Enter fullscreen mode Exit fullscreen mode

This one line is the difference between "okay" and "feels expensive."


The Snap Back to Plain Text

Here's a small but important detail.

While the animation is running, the Box contains the full drum string (5\n4\n3\n2). When the animation finishes, the visible character is 5 — but the composable still holds the whole string, just clipped.

Why does that matter? Because of sub-pixel rendering. Text engines, including Compose, do tiny adjustments based on surrounding glyphs. A 5 that lives inside a multi-line drum is positioned slightly differently than a standalone 5. The difference is maybe one pixel — but you can see it.

So at the end of the animation, I replace the drum string with just the final character:

try {
    isAnimating = true
    progress.snapTo(0f)
    progress.animateTo(
        targetValue = 1f,
        animationSpec = tween(
            durationMillis = 500,
            easing = RollingEasing,
        )
    )
} finally {
    drumText = char.toString()   // ← snap to clean state
    previousChar = char
    isAnimating = false
    linePositions = emptyList()
}

Enter fullscreen mode Exit fullscreen mode

The finally block makes sure this clean-up happens even if the animation is cancelled — for example, when the user changes the value before the previous roll has finished.


Autosize: Making It Fit

In a crypto ticker, you never know how long the number will be. $1.23 and $67,543.21 may have to fit into the same box.

I wanted the text to shrink automatically when needed. The trick is BoxWithConstraints plus a TextMeasurer:

BoxWithConstraints(modifier = modifier) {
    val textMeasurer = rememberTextMeasurer()
    val maxWidth = constraints.maxWidth

    val adjustedStyle = remember(displayedValue, maxWidth, style) {
        if (maxWidth > 0 && maxWidth != Constraints.Infinity) {
            calculateFontSizeToFit(
                text = displayedValue,
                style = style,
                maxWidth = maxWidth,
                textMeasurer = textMeasurer,
            )
        } else {
            style
        }
    }
    // ...
}

Enter fullscreen mode Exit fullscreen mode

calculateFontSizeToFit starts with the requested font size and steps down by 1sp until the text fits. It's not a clever algorithm — but font sizes are small numbers (roughly 10 to 60), so it's fast enough.


Inside buildDrumText

This is the function that builds the drum string. It's tiny:

private fun buildDrumText(from: Char, to: Char): String {
    val start = from.digitToInt()
    val end = to.digitToInt()

    return if (end > start) {
        (end downTo start).joinToString("\n")
    } else {
        (start downTo end).joinToString("\n")
    }
}

Enter fullscreen mode Exit fullscreen mode

Notice that both branches use downTo. The string is always ordered from highest to lowest, top-to-bottom. The direction of the animation (rolling up or rolling down) is handled separately, by inverting the progress:

val adjustedProgress = if (isIncreasing) 1f - progress.value else progress.value

Enter fullscreen mode Exit fullscreen mode

When the digit is increasing (2 → 5), I flip the progress so the drum slides from "bottom visible" to "top visible" — the new digit falls down from above. When it's decreasing (5 → 2), the drum slides the natural way — the new digit rises up from below. It matches how a real odometer behaves.


The Evil Math: calculateVerticalOffset

This one took me a while to get right.

private fun calculateVerticalOffset(
    progress: Float,
    linePositions: List<Float>,
    lineHeight: Float,
    linesCount: Int,
): Float = when {
    linePositions.size >= linesCount -> {
        -(linePositions[linesCount - 1] - linePositions[0]) * progress
    }
    lineHeight > 0f -> {
        -progress * (linesCount - 1) * lineHeight
    }
    else -> 0f
}

Enter fullscreen mode Exit fullscreen mode

Two branches:

  1. If we have real measured line positions (from TextLayoutResult.getLineTop()), use them. This is the accurate path — different fonts and glyphs have slightly different line heights, and measuring them gives a pixel-perfect offset.
  2. If we don't have line positions yet (the very first frame, before the text has been laid out), fall back to lineHeight × (linesCount - 1). It's an estimate, but it's close, and the next frame will already use the real measurements. Why the minus sign? Because Compose's Y axis grows downward. To slide the text up (so the next digit comes into view), we need a negative translation.

Try It

RollingAnimatedText(
    text = "$67,543.21",
    style = MaterialTheme.typography.headlineLarge,
    autoSize = true,
)

Enter fullscreen mode Exit fullscreen mode

That's it. Drop it in, it rolls.

The library is on GitHub: github.com/morozione/compose-rolling-text. Stars, issues, and pull requests are very welcome — especially if you find a use case I didn't think of (a countdown timer? a stock ticker? a leaderboard score?).


What I Learned

Building this taught me three small things that I'll carry into the next project:

  1. graphicsLayer is a superpower. Anytime you can move pixels without touching layout, you should. It's faster, smoother, and side-effect-free.
  2. Sub-pixel details matter. The post-animation snap is the difference between "good" and "polished." Users won't be able to name what's wrong without it, but they'll feel it.
  3. Look for the simplest mental model. A single multi-line string was much better than ten stacked composables. The first idea isn't always the right idea. Thanks for reading. Now go build something smooth.