如何在android compose中以黑白显示图像
我正在尝试使用android compose将显示的彩色图像转换为黑白。如何在android compose中以黑白显示图像,android,kotlin,android-jetpack-compose,Android,Kotlin,Android Jetpack Compose,我正在尝试使用android compose将显示的彩色图像转换为黑白。 在视图系统中,我可以通过添加这样的过滤器将图像从彩色更改为黑白 imageView.colorFilter=ColorMatrixColorFilter(ColorMatrix()。应用{setSaturation(0f)}) 如图所示。 在Android Compose中,Imagecomposable函数已经使用了颜色过滤器,但我在Compose包中找不到ColorMatrixColorFilter等价物。 这是我想
在视图系统中,我可以通过添加这样的过滤器将图像从彩色更改为黑白
imageView.colorFilter=ColorMatrixColorFilter(ColorMatrix()。应用{setSaturation(0f)})
如图所示。在Android Compose中,Imagecomposable函数已经使用了颜色过滤器,但我在Compose包中找不到ColorMatrixColorFilter等价物。
这是我想转换成灰度的图像代码
图像(
资产=矢量资源(id=R.drawable.xxx),
修改器=修改器.剪辑(矩形形状).大小(36.dp,26.dp),
α=α,
对齐=对齐。居中,
contentScale=contentScale.Fit
)
我尝试了这个答案并为我工作:
所以,您只需要使用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
}
我希望我没有误解这个问题,但这帮助我将图像转换为灰度。这与当前的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)
)
我使用的是drawable而不是位图,因此我不能使用
BitmapFactory.decodeResource(context.resources,R.drawable.ic_launcher)
您可以将任何drawable转换为位图。。。androidx核心库(androidx.core:coreKTX)现在有一个扩展函数来实现这一点。。。我用ShapeDrawable拍摄了一张照片,效果很好……我编辑了我的答案,使用了一张Drawable
。你能解释一下你的代码吗,特别是灰度矩阵值