【问题标题】:How to show Image in black and white in android compose如何在android compose中以黑白显示图像
【发布时间】:2020-12-02 07:15:10
【问题描述】:

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

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

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

answer所示。

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

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

 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 kotlin android-jetpack-compose


    【解决方案1】:

    我希望我没有误解这个问题,但这有助于我将图像转换为灰度。这是根据当前 Compose 版本 1.0.0-beta01

    val grayScaleMatrix = ColorMatrix(
            floatArrayOf(
                0.33f, 0.33f, 0.33f, 0f, 0f,
                0.33f, 0.33f, 0.33f, 0f, 0f,
                0.33f, 0.33f, 0.33f, 0f, 0f,
                0f, 0f, 0f, 1f, 0f
            )
        )
    Image(
            painter = painterResource(id = imageId),
            contentDescription = "",
            colorFilter = ColorFilter.colorMatrix(matrix)
        )
    

    【讨论】:

    • 您能否详细解释一下您的代码,尤其是 grayScaleMatrix 值
    【解决方案2】:

    我尝试了这个答案并为我工作: Convert a Bitmap to GrayScale in Android

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

    这就是我所做的:

    @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
    }
    

    【讨论】:

    • 我使用的是drawables而不是位图,所以我不能使用BitmapFactory.decodeResource( context.resources,R.drawable.ic_launcher)
    • 您可以将任何 Drawable 转换为位图... androidx 核心库 (androidx.core:core-ktx) 现在有一个扩展功能可以做到这一点... 我用 ShapeDrawable 进行了拍摄它奏效了......
    猜你喜欢
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 2012-04-28
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多