0

I have here my code which just displays a simple color palette:

@Composable
fun ColorPicker(modifier: Modifier = Modifier) {
    Box(
        modifier = modifier
            .fillMaxSize()
            .background(Brush.horizontalGradient(colors()))
    ) {

    }
}

fun colors(n: Int = 359): List<Color> {
    val cols = mutableListOf<Color>()
    for (i in 0 until n) {
        val color = java.awt.Color.getHSBColor(i.toFloat() / n.toFloat(), 0.85f, 1.0f)
        cols.add(Color(color.red, color.green, color.blue, color.alpha))
    }
    return cols
}

That looks pretty good:

Click here

But now I want to get the RGB Value if the usere clicks on the color palette. How would I do this? (This is Jetpack Compose Desktop but it should be the same as on Android)

Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
Jan
  • 9
  • 4
  • I don't know if that is a good way but it worked using clickable and the Robot class. So on click I just get the rgb on the current mouse position. – Jan Jul 07 '21 at 19:30

1 Answers1

0

You could instead create Cards of a very small width for each colour and modify a state holder from their onClicks

For example,

var rgb by mutableStateOf ("") // displays RGB values
Text(rgb)
Layout( content = {
for (i in 0 until 359) {

        val color =
 java.awt.Color.getHSBColor(i.toFloat() / n.toFloat(), 0.85f, 1.0f)

        Card(
                   Modifier.background(Color(
                                                                      color.red, 
                                                                      color.green, 
                                                                      color.blue, 
                                                                      color.alpha
                                                                    )
                                                          ),
                  onClick = { rgb = color. // Assign appropriate value
                  }
    
}
){measurables, constraints -> 
val placeables = measurables.map{
it.measure(constraints.maxWidth/measurables.size, constraints.maxHeight)
} 
int x = 0
layout(constraints.maxWidth, constraints.maxHeight){
placeables.forEach{
it.placeRelative(x, 0)
x+=it.width
}
}
}

This distributes width equally

Richard Onslow Roper
  • 5,477
  • 2
  • 11
  • 42