Reputation: 3227
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)})
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
)
Upvotes: 7
Views: 4017
Reputation: 13562
I hope I have not misunderstood the problem but this helped me convert the image into grayscale. This is as per the current Compose version 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)
)
Upvotes: 9
Reputation: 23964
I tried this answer and worked for me: Convert a Bitmap to GrayScale in Android
So, you just need to use toGrayscale
function...
This is what I did:
@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
}
Upvotes: 0