How to add Gradient colors in Text using Brush and TextStyle in Jetpack Compose
In Jetpack Compose, we can easily change the appearance of components using various tools. On this occasion, we will use Brush
to add a gradient effect in different positions and TextStyle
to apply them.
What is Brush?
Brush
is a class that represents a gradient or a solid color. It is used to define the fill or stroke color of a shape.- The
linearGradient
,horizontalGradient
,verticalGradient
,radialGradient
, andsweepGradient
methods are extension functions of theBrush
class that create instances of different gradient types. - Gradients are used to create smooth transitions between multiple colors.
What is TextStyle?
TextStyle
is a class used to define the style of text, such as font size, font weight, color, and other text-related properties.- In the provided code,
TextStyle
is used to specify the style of the text within theTextWithStyle
composable. - It includes properties like
textAlign
for the alignment of the text,lineHeight
for controlling the height of lines,textIndent
for indentation, andbrush
for specifying the text color or gradient.
First, let’s create a list of colors that will be used in this example.
/**
* Returns a list of gradient colors for demonstration purposes.
* Customize the colors based on your preferences or design requirements.
*/
fun getGradientColors(): List<Color> {
return listOf(Color.Black, Color.Cyan, Color.Blue, Color.Green, Color.Red /*...*/)
}
Afterward, we will create a function that will be reused to apply the text style along with the brush to a Text component.
/**
* A composable function to display text with specified styling and a gradient background.
*
* @param previewText The text to be displayed.
* @param brush The brush defining the gradient background.
* @param modifier The modifier for additional styling options.
*/
@Composable
fun TextWithStyle(previewText: String, brush: Brush, modifier: Modifier = Modifier) {
val textStyle = TextStyle(
textAlign = TextAlign.Justify,
lineHeight = 20.sp,
textIndent = TextIndent(firstLine = 14.sp, restLine = 3.sp),
brush = brush
)
Text(
text = previewText,
modifier = modifier.padding(16.dp),
style = textStyle
)
}
This code defines a TextStyle
object, which is used to specify the visual styling of text in Jetpack Compose. Let's break down the properties:
textAlign
: It determines the horizontal alignment of the text. In this case, it is set toTextAlign.Justify
, which means the text will be justified, i.e., it will be stretched to fill the width of the container.lineHeight
: It sets the height of each line of text. In this example, it is set to20.sp
, indicating a line height of 20 density-independent pixels.textIndent
: It specifies the indentation for the first line and the rest of the lines in the text. Here, it is set toTextIndent(firstLine = 14.sp, restLine = 3.sp)
, meaning the first line will have an indentation of 14 density-independent pixels, and the rest of the lines will have an indentation of 3 density-independent pixels.brush
: It defines the brush used for drawing the text. In this case, the brush is provided as a parameter to theTextStyle
constructor.
In the context of the provided code, the TextStyle
is configured to create a stylized text appearance with justified alignment, a specific line height, text indentation for the first and rest lines, and a gradient brush applied to the text. This TextStyle
can be further applied to a Text
component to display text with the defined styling.
We will use this constant to obtain the text that we are going to use in these examples.
const val PREVIEW_TEXT =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod " +
"tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud " +
"exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor " +
"in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur " +
"sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est" +
" laborum."
We will start with LinearGradient function.
Creates a linear gradient with the provided colors, you can also give it start or end coordinates.
/**
* A composable function to demonstrate text rendering with a linear gradient background.
*
* @param previewText The text to be displayed in the example.
*/
@Composable
fun LinearGradientExample(previewText: String) {
val brush = remember { Brush.linearGradient(colors = getGradientColors()) }
TextWithStyle(previewText = previewText, brush)
}
We continue with HorizontalGradient function.
Creates a horizontal gradient with the given colors evenly dispersed within the gradient.
/**
* A composable function to demonstrate text rendering with a horizontal gradient background.
*
* @param previewText The text to be displayed in the example.
*/
@Composable
fun HorizontalGradientExample(previewText: String) {
val brush = remember { Brush.horizontalGradient(colors = getGradientColors()) }
TextWithStyle(previewText = previewText, brush)
}
Now, we will use VerticalGradient function.
Creates a vertical gradient with the given colors evenly dispersed within the gradient.
/**
* A composable function to demonstrate text rendering with a vertical gradient background.
*
* @param previewText The text to be displayed in the example.
*/
@Composable
fun VerticalGradientExample(previewText: String) {
val brush = remember { Brush.verticalGradient(colors = getGradientColors()) }
TextWithStyle(previewText = previewText, brush)
}
We will proceed with RadialGradient function.
Creates a radial gradient with the given colors evenly dispersed within the gradient.
/**
* A composable function to demonstrate text rendering with a radial gradient background.
*
* @param previewText The text to be displayed in the example.
*/
@Composable
fun RadialGradientExample(previewText: String) {
val brush = remember { Brush.radialGradient(colors = getGradientColors()) }
TextWithStyle(previewText = previewText, brush)
}
And we finish with SweepGradient function.
Creates a sweep gradient with the given colors dispersed evenly around the center. The sweep begins relative to 3 o’clock and continues clockwise until it reaches the starting position again.
/**
* A composable function to demonstrate text rendering with a sweep gradient background.
*
* @param previewText The text to be displayed in the example.
*/
@Composable
fun SweepGradientExample(previewText: String) {
val brush = remember { Brush.sweepGradient(colors = getGradientColors()) }
TextWithStyle(previewText = previewText, brush)
}
You can also use it in TextField and its variants.
/**
* A composable function demonstrating the usage of a vertical gradient in an OutlinedTextField.
*
* @sample [OutlinedTextFieldExample]
*/
@Composable
fun OutlinedTextFieldExample() {
// State variable to store the text input
var text by rememberSaveable { mutableStateOf("") }
// Create a vertical gradient brush using predefined colors
val brush = remember { Brush.verticalGradient(colors = getGradientColors()) }
// Define the text style with the vertical gradient
val textStyle = TextStyle(
textAlign = TextAlign.Justify,
lineHeight = 20.sp,
textIndent = TextIndent(firstLine = 14.sp, restLine = 3.sp),
brush = brush
)
// OutlinedTextField composable to capture user input
OutlinedTextField(
value = text,
enabled = true,
onValueChange = { newValue ->
text = newValue
},
label = { Text(text = "Gradient Example", fontSize = 14.sp, color = Color.Black) },
textStyle = textStyle,
modifier = Modifier.fillMaxWidth(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
maxLines = 5
)
}