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.

Gradient Background Custom Modifier
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.

Aspect Ration Custom Modifier
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 —

  1. Elevation Modifier: Apply elevation to a composable, giving it a subtle shadow for a sense of depth.
  2. Underline Modifier: Add an underline to a text composable, creating emphasis.
  3. Circular Progress Modifier: Display a circular progress indicator around a composable.
  4. Image Tint Modifier: Change the tint color of an image to match your app’s color scheme.
  5. Parallax Scroll Modifier: Apply a parallax effect to a composable when it’s scrolled.
  6. Slidable Modifier: Create a slidable panel effect for a composable, revealing hidden content.
  7. Custom Border Modifier: Add a customized border to a composable, with options for width, color, and shape.
  8. Animated Scale Modifier: Apply a scaling animation to a composable to enhance interaction.
  9. Loading State Modifier: Modify a composable to display a loading state with a progress indicator.

Here’s another custom modifier just for the fun of it!

Floating Action Button Animator Custom Modifier

Source link