Unleashing Creativity with Custom Modifiers in Android Jetpack Compose | by Nirbhay Pherwani | Aug, 2023
Mobile App Development
0
Example 1 — Gradient Background Modifier
Create a custom modifier that applies a gradient background to a composable. This can be used to provide a consistent visual theme across your app’s components.
fun Modifier.gradientBackground(colors: List<Color>): Modifier = composed {
drawWithContent {
drawRect(
brush = Brush.verticalGradient(colors),
size = size
)
drawContent()
}
}
Usage —
Column(
modifier = Modifier
.gradientBackground(listOf(Color.Blue, Color.Green, Color.White))
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Text("Custom modifier was applied on me!")
}
Example 2 — Aspect Ratio Modifier
Design a custom modifier that enforces a specific aspect ratio for an image. This ensures that images maintain a consistent look across various screens.
fun Modifier.aspectRatio(ratio: Float): Modifier = composed {
layout { measurable, constraints ->
val width = constraints.maxWidth
val height = (width / ratio).toInt()
val placeable = measurable.measure(
constraints.copy(minHeight = height, maxHeight = height)
)
layout(width, height) {
placeable.place(0, 0)
}
}
}
Usage —
Image(
painter = painterResource(id = R.drawable.stock_wallapaper),
contentDescription = null,
modifier = Modifier
.aspectRatio(16/9f)
.fillMaxWidth(), // modify as needed
contentScale = ContentScale.Crop
)
Some more example ideas for custom modifiers —
- Elevation Modifier: Apply elevation to a composable, giving it a subtle shadow for a sense of depth.
- Underline Modifier: Add an underline to a text composable, creating emphasis.
- Circular Progress Modifier: Display a circular progress indicator around a composable.
- Image Tint Modifier: Change the tint color of an image to match your app’s color scheme.
- Parallax Scroll Modifier: Apply a parallax effect to a composable when it’s scrolled.
- Slidable Modifier: Create a slidable panel effect for a composable, revealing hidden content.
- Custom Border Modifier: Add a customized border to a composable, with options for width, color, and shape.
- Animated Scale Modifier: Apply a scaling animation to a composable to enhance interaction.
- Loading State Modifier: Modify a composable to display a loading state with a progress indicator.