Changing an ImageView to black and white
You can simply achieve this by doing:
ImageView imageview = (ImageView) findViewById(R.id.imageView1);
ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
imageview.setColorFilter(filter);
This is the Kotlin Version
imageView.colorFilter = ColorMatrixColorFilter(ColorMatrix().apply { setSaturation(0f)})
You can use android.graphics.ColorFilter
for your purpose.
You can use this sample to suite your need.
Pass the imageView
to the setBW
method like
setBW(imageView);
and the the functionality is
private void setBW(ImageView iv){
float brightness = 10; // change values to suite your need
float[] colorMatrix = {
0.33f, 0.33f, 0.33f, 0, brightness,
0.33f, 0.33f, 0.33f, 0, brightness,
0.33f, 0.33f, 0.33f, 0, brightness,
0, 0, 0, 1, 0
};
ColorFilter colorFilter = new ColorMatrixColorFilter(colorMatrix);
iv.setColorFilter(colorFilter);
}
Try using this. Any concerns. Let me know. Thanks.
I would also suggest using Kotlin extensions:
private const val MAX_SATURATION = 1f
private const val MIN_SATURATION = 0f
fun ImageView.setMaxSaturation() {
val matrix = ColorMatrix()
matrix.setSaturation(MAX_SATURATION)
colorFilter = ColorMatrixColorFilter(matrix)
}
fun ImageView.setMinSaturation() {
val matrix = ColorMatrix()
matrix.setSaturation(MIN_SATURATION)
colorFilter = ColorMatrixColorFilter(matrix)
}