Open In App

Android Jetpack Compose – Creating a Color Picker Using Material 3 Slider Component

Last Updated : 21 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we’ll explore how to create a color picker using Jetpack Compose, leveraging Material 3 Slider components. A color is essentially a combination of different amounts of red, green, blue, and alpha values, and we’ll manage these values using sliders in our color picker UI. A sample video is given below to get an idea about what we are going to do in this article.



Prerequisites:

Before diving into the tutorial, make sure you have a Basic Understanding of Jetpack Compose, the latest version of Android Studio installed and a Jetpack Compose project setup.

Step by Step Implementation

UI Design

Our color picker UI will consist of a box to represent the currently selected color and four sliders for adjusting the red, green, blue, and alpha values.

Step 1: Setting Up the Project

First, ensure that your project has Jetpack Compose and Material 3 dependencies added as mentioned in the prerequisites. To get started, we’ll need to add the necessary dependencies to our project’s app module `build.gradle` file:

dependencies {
implementation(platform("androidx.compose:compose-bom:2024.02.00"))

implementation("androidx.compose.ui:ui")
implementation("androidx.compose.material3:material3")
implementation("androidx.compose.ui:ui-tooling-preview")
debugImplementation("androidx.compose.ui:ui-tooling")

// Other dependencies
}

Step 2: Creating the Color Picker Composable

We’ll create a composable function named ColorPicker to encapsulate our color picker UI. This function will include sliders for adjusting the RGBA values and will display the current color in a box.

Kotlin
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

@Composable
fun ColorPicker() {
    // State variables for RGBA values
    val alpha = rememberSaveable { mutableFloatStateOf(1f) }
    val red = rememberSaveable { mutableFloatStateOf(0f) }
    val green = rememberSaveable { mutableFloatStateOf(0f) }
    val blue = rememberSaveable { mutableFloatStateOf(0f) }

    // Derived state for the color based on RGBA values
    val color by remember {
        derivedStateOf {
            Color(red.value, green.value, blue.value, alpha.value)
        }
    }

    // UI layout using Scaffold and Column
    Scaffold(
        topBar = { TopAppBar(title = { Text("Color Picker") }) }
    ) {
        Column(modifier = Modifier.padding(it)) {
            // Display the current color in a Box with a MaterialTheme shape
            Row {
                Box(
                    modifier = Modifier
                        .padding(10.dp, 0.dp)
                        .fillMaxWidth()
                        .height(80.dp)
                        .background(color, shape = MaterialTheme.shapes.large)
                )
            }

            // Sliders for adjusting RGBA values
            Column(
                modifier = Modifier.padding(12.dp),
                verticalArrangement = Arrangement.spacedBy(5.dp)
            ) {
                ColorSlider("A", alpha, color.copy(1f))
                ColorSlider("R", red, Color.Red)
                ColorSlider("G", green, Color.Green)
                ColorSlider("B", blue, Color.Blue)
            }
        }
    }
}

Step 3: Creating the ColorSlider Composable

Next, we’ll define a composable function named `ColorSlider` to create individual sliders for adjusting the RGBA values. This function will take a label, a mutable state for the slider value, and a color for the slider’s active track.

Kotlin
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.width
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp

/**
 * A composable function that creates a slider for adjusting a float value associated with a color.
 *
 * @param label The label to display alongside the slider.
 * @param valueState The mutable state holding the current value of the slider.
 * @param color The color used for the active track of the slider.
 */
@Composable
fun ColorSlider(
    label: String,
    valueState: MutableState<Float>,
    color: Color,
) {
    /**
     * Displays a slider for adjusting the given [valueState] associated with the provided [label].
     * The slider's active track color is set to [color].
     */
    Row(
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(6.dp)
    ) {
        Text(text = label)
        Slider(
            value = valueState.value,
            onValueChange = valueState.component2(),
            colors = SliderDefaults.colors(
                activeTrackColor = color
            ),
            modifier = Modifier.weight(1f)
        )
        Text(
            text = valueState.value.toColorInt().toString(),
            modifier = Modifier.width(25.dp),
            textAlign = TextAlign.End,
            style = MaterialTheme.typography.bodySmall
        )
    }
}

Step 4: Adding Utility Functions

We’ll also include an extension function `toColorInt()` to convert float values to integer color components.

Kotlin
import androidx.compose.ui.graphics.Color

/**
 * Converts a float value in the range [0, 1] to an integer color component in the range [0, 255].
 *
 * @return The integer representation of the color component.
 */
fun Float.toColorInt(): Int = (this * 255 + 0.5f).toInt()

Output:

We can use the ColorPicker Composable in Activity or other composables.

Conclusion

In this tutorial, we’ve learned how to create a color picker using Jetpack Compose and Material 3 Slider components. By adjusting the RGBA values with sliders, users can easily select their desired colors.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads