Skip to content

Instantly share code, notes, and snippets.

@nisrulz
Created December 25, 2015 05:52
Show Gist options
  • Save nisrulz/3078eaa6357d6f5c0051 to your computer and use it in GitHub Desktop.
Save nisrulz/3078eaa6357d6f5c0051 to your computer and use it in GitHub Desktop.
Apply grayscale filter to ImageView in android
ImageView imgview = (ImageView)findViewById(R.id.imageView_grayscale);
imgview.setImageBitmap(bitmap);
// Apply grayscale filter
ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
imgview.setColorFilter(filter);
@Anand-Selot
Copy link

I want to apply this grayscale filter to 1/5 or 1/2 of the image horizontally... any help would be great.

@cdj3579
Copy link

cdj3579 commented Jul 1, 2019

I want to apply this grayscale filter to 1/5 or 1/2 of the image horizontally... any help would be great.

I have implement a simple ProgressImageView according to it, hope this will help you.

class ProgressImageView(context: Context?, attrs: AttributeSet?) : ImageView(context, attrs) {

    private val grayFilter: ColorMatrixColorFilter = ColorMatrixColorFilter(ColorMatrix().apply { setSaturation(0.0f) })

    var progress = 0.0f

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)

        val h = height.times(1.0f - progress).roundToInt()
        if (h > 0) {
            canvas?.clipRect(0, 0, width, h)
            val oldFilter = colorFilter
            colorFilter = grayFilter
            super.onDraw(canvas)
            colorFilter = oldFilter
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment