Home > Blockchain >  How to draw border depending of color of loaded image?
How to draw border depending of color of loaded image?

Time:06-11

I load the image by url using the coil library. After loading I need to draw a border around the image depending of background color of uploaded picture. For example, if I loaded the picture with white background, I need to set black border.

    val painter = 
            rememberAsyncImagePainter(
                ImageRequest.Builder(LocalContext.current)
                .data(data = imageUrl)
                .apply(block = fun ImageRequest.Builder.() {
                    crossfade(true)
                    allowHardware(false)
                }).build()
            )
        val painterState = painter.state
        Image(
            painter = painter,
            contentDescription = null,
            modifier = Modifier
                .padding(start = 20.dp, top = 20.dp)
                .width(130.dp)
                .height(68.dp)
        )

When painter.state is Succes, i'm picking the color of loaded drawable with Palette library.

How can I access to image after successful loading and draw the border in needed color?

CodePudding user response:

I assume you mean

by How can I access to image after successful

exact bounds of area is ImageBitmap drawn inside Image with ContentScale. If that's the issue i built a library that returns exact bounds and which section of image is drawn but since i'm not sure not adding sample with it. If you don't need exactly the bounds check the answer below

You can define a Color with var color by remember {mutableStateOf(Color.Unspecified)

Modifier.border(x.dp, color) will be recomposed when this color changes. After getting desired color from Palette Api if you set color = colorVibrant for instance, you will be able to draw border around your Image with correct dimensions.

State check here is for creating a producible sample

val painter =
    rememberAsyncImagePainter(
        ImageRequest.Builder(LocalContext.current)
            .data(data = "https://source.unsplash.com/pGM4sjt_BdQ")
            .apply(block = fun ImageRequest.Builder.() {
                crossfade(true)
                allowHardware(false)
            }).build()
    )

var color by remember { mutableStateOf(Color.Unspecified) }
val painterState = painter.state

if (painterState is AsyncImagePainter.State.Success) {
    color = Color.Red
}

Column() {
    Spacer(Modifier.height(50.dp))
    Text("PainterState State: ${painterState.painter}")
    Image(
        painter = painter,
        contentDescription = null,
        modifier = Modifier
            .padding(start = 20.dp, top = 20.dp)
            .border(2.dp, color)
            .width(300.dp)
            .height(268.dp)
    )
}

enter image description here

  • Related