如何在android compose中以黑白显示图像 [英] How to show Image in black and white in android compose

查看:39
本文介绍了如何在android compose中以黑白显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 android compose 将显示的彩色图像转换为黑白图像.

在视图系统中,我可以通过添加这样的过滤器将图像从彩色变为黑白

I am trying to convert the colored Image shown to black and white using android compose.

In the view system, I could change the image from colored to black and white by adding a filter like that

imageView.colorFilter = ColorMatrixColorFilter(ColorMatrix().apply { setSaturation(0f)})

如本答案所示.

在 Android Compose 中,Image 可组合函数已经采用颜色过滤器,但我在 compose 包中找不到等效的 ColorMatrixColorFilter.

这是我想转换为灰度的图像代码

as shown in this answer.

In Android Compose the Image composable function already takes color filter but I cannot find ColorMatrixColorFilter equivalent in the compose package.

Here is the Image code that I want to convert to grayscale

 Image(
            asset = vectorResource(id = R.drawable.xxx),
            modifier = Modifier.clip(RectangleShape).size(36.dp, 26.dp),
            alpha = alpha,
            alignment = Alignment.Center,
            contentScale = ContentScale.Fit
        )

推荐答案

我尝试了这个答案并为我工作:在 Android 中将位图转换为灰度

I tried this answer and worked for me: Convert a Bitmap to GrayScale in Android

所以,你只需要使用 toGrayscale 函数...

So, you just need to use toGrayscale function...

这就是我所做的:

@Composable
fun GrayscaleImage() {
    val context = AmbientContext.current
    val image = remember {
        val drawable = ContextCompat.getDrawable(
            context, R.drawable.your_drawable
        ).toBitmap()!!.toGrayScale().asImageBitmap()
    }
    Image(image)
}


object Constants{
    val grayPaint = android.graphics.Paint()
    init {
        val cm = ColorMatrix()
        cm.setSaturation(0f)
        val f = ColorMatrixColorFilter(cm)
        grayPaint.colorFilter = f
    }
}


fun Bitmap.toGrayscale(): Bitmap {
    val height: Int = this.height
    val width: Int = this.width
    val bmpGrayscale: Bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
    val c = Canvas(bmpGrayscale)
    c.drawBitmap(this, 0f, 0f, Constants.grayPaint)
    return bmpGrayscale
}

这篇关于如何在android compose中以黑白显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆