Android Compose에서 이미지를 흑백으로 표시하는 방법

Dec 02 2020

android compose를 사용하여 표시된 컬러 이미지를 흑백으로 변환하려고합니다.

뷰 시스템에서 이와 같은 필터를 추가하여 이미지를 컬러에서 흑백으로 변경할 수 있습니다.

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

이 답변에 표시된대로 .

Android Compose에서 Image composable 함수는 이미 컬러 필터를 사용하지만 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
        )

답변

nglauber Jan 09 2021 at 20:59

이 대답을 시도하고 나를 위해 일했습니다 . 비트 맵을 Android에서 GrayScale로 변환

따라서 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
}