Color Picker in Compose

Abhilash
ProAndroidDev
Published in
3 min readMay 20, 2023

--

For my first article in medium, I would like to start by showing you how to create a color picker in pure compose.

Photo by Frans van Heerden on Pexels

Usually color pickers will have 3 components,

  1. Hue — The color of the picker
  2. Saturation — The intensity of the color
  3. Value — The lightness of the color

We are going to have 2 panels. One will contain the hue selector and other panel will have both saturation and value in it.

First we will start by having hue panel. The output should look something like this.

(Since it would not look nice to have to write android.graphics.Color or androidx.compose.ui.graphics.Color in all the places that we use. We will import android.graphics.Color as AndroidColor)

For that we would have to draw in canvas.

We will be drawing this hue gradient in bitmap using android.graphics.Canvas.

Now we will split these colors across the width of the huePanel.

Drawing each line of color in canvas would look like

Finally drawing this into our compose canvas

Next step is to have a offset state to observe where user is touching and drawing a circle to that area.

Note: We have to draw this circle after drawing bitmap, else it will just be overdrawn by bitmap.

We have to send a callback for when hue is changed with click and also with drag.

Luckily we can not only get click position using InteractionSource but also send pressPosition to it. This way we only need to observe for it in one place.

We will write a custom Modifier to achieve this.

We have to observe for click and drag to find out exactly which hue is user picking.

Now the hue panel is all set. After a little bit of cleaning code will look something like this.

Next is a panel which is used to select saturation and value.

The basic upto creating a Canvas for bitmap is same as that of HuePanel.

Since we are creating a panel that contains both saturation and value, we will create saturation gradient from top-left to top-right and value gradient from top-left to bottom-left.

The rgb value is calculated under the assumption that hue is passed to this composable.

Next we will draw a rounded rectangle by combining the satShader and valShader using Compose Shader.

Drawing the Saturation + Value panel is over. Now we need to observe and draw a circle where our user will click/drag and then convert that position into saturation and value.

Finally our composable will look like this.

Getting value from both of those panel and set it where ever you like.

Our output will look like this.

Compose Color picker in Emulator

Any criticism is welcomed. Kindly post it in comments.

--

--