drawWithCache y rendimiento
Evite reconstruir los objetos de dibujo en cada fotograma.
drawWithCache y rendimiento es una lección gratuita de Jetpack Compose Academy en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Jetpack Compose Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Jetpack Compose Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Drawing Runs Often
Your Canvas lambda can run on every frame. Rebuilding heavy objects there, frame after frame, quietly drags down performance.
The Costly Objects
Things like Path, Brush, and Paint are not free to create. Allocating them on each draw wastes work the GPU never needed.
Enter drawWithCache
The drawWithCache modifier lets you build expensive objects once and reuse them. It splits setup from the actual drawing step.
Modifier.drawWithCache {
// build once here
onDrawBehind { /* draw each frame */ }
}Build Block Runs Rarely
Code in the cache block only re-runs when the size or your read state changes. Put your Path and Brush creation right here.
Modifier.drawWithCache {
val brush = Brush.linearGradient(colors)
onDrawBehind { drawRect(brush) }
}onDrawBehind
Use onDrawBehind to paint underneath the Composable's content. It gives you a DrawScope that runs on each frame, cheaply.
onDrawBehind {
drawCircle(color = Color.Blue)
}onDrawWithContent
Need to mix your art with the actual UI? onDrawWithContent lets you draw, call drawContent, and draw again around it.
onDrawWithContent {
drawContent()
drawRect(color = Color.Black, alpha = 0.2f)
}Cache the Path
A chart Path is a classic win. Build it once in the cache block, then just drawPath it every frame without rebuilding.
val path = Path().apply { /* shape */ }
onDrawBehind { drawPath(path, Color.Green) }React to Size
Inside the cache block you can read size safely. When the canvas resizes, your block re-runs and rebuilds objects to fit.
Avoid State Reads in Draw
Reading state during drawing can trigger extra work. Keep your draw block lean and move setup into the cache block instead.
Measure, Do Not Guess
Before optimizing, profile. The Layout Inspector and frame timings tell you what really stutters, so you fix the right thing.
Reuse Wherever You Can
The golden rule: build heavy objects once and reuse them. drawWithCache makes that pattern easy and your animations buttery smooth.
Quick Check
Where should you create an expensive Brush so it is not rebuilt every frame?
Recap
You learned to keep drawing fast: build heavy objects in the drawWithCache block, draw cheaply in onDrawBehind, and always measure first. Smooth frames! ⚡
Preguntas frecuentes
¿La lección «drawWithCache y rendimiento» es gratis?
Sí — el texto completo de «drawWithCache y rendimiento» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Jetpack Compose Academy, actualiza a CoddyKit PRO. El curso de Jetpack Compose Academy incluye 4 lecciones en total.
¿Qué aprenderé en «drawWithCache y rendimiento»?
Evite reconstruir los objetos de dibujo en cada fotograma. Practicas Jetpack Compose Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Jetpack Compose Academy?
No se requiere experiencia previa. Jetpack Compose Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.
¿Cuánto tiempo toma la lección «drawWithCache y rendimiento»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Jetpack Compose Academy?
Sí. Cada lección de Jetpack Compose Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- DrawScope: líneas, rectángulos y círculos
- Trazados, degradados y modos de mezcla
- drawWithCache y rendimiento
- Crear un anillo de progreso en tiempo real