Mimicking PorterDuff overlay mode using ColorMatrix to overlay a solid color

410 views Asked by At

I have the following code that reduces an image's contrast and by 50% and turns down the saturation to 0. Works flawlessly. However, I need to overlay a give colour over the resulting image, much like the PorterDuff.Mode.OVERLAY filter.

I've been fiddling with this for hours, didn't get me anywhere close to what I wanted.

        float contrast = -0.5f;
        float scale = contrast + 1.f;
        float translate = (-.5f * scale + .5f) * 255.f;
        float[] array = new float[]{
                scale, 0, 0, 0, translate,
                0, scale, 0, 0, translate,
                0, 0, scale, 0, translate,
                0, 0, 0, 1, 0};
        ColorMatrix contrastMatrix = new ColorMatrix(array);
        ColorMatrix saturationMatrix = new ColorMatrix();
        saturationMatrix.setSaturation(0);
        ColorMatrix matrix = new ColorMatrix();
        matrix.setConcat(contrastMatrix, saturationMatrix);
        // This is where I've been trying to overlay the colour by fiddling the colour matrix array.
        // Didn't get the effect I wanted.
        int primaryColor = context.getResources().getColor(R.color.primary500);
        matrix.postConcat(new ColorMatrix(
            new float[]{
                    Color.red(primaryColor)/255f, 0, 0, 0, 0,
                    0, Color.green(primaryColor)/255f, 0, 0, 0,
                    0, 0, Color.blue(primaryColor)/255f, 0, 0,
                    0, 0, 0, 1, 0}));
        imageView.setColorFilter(filter);

The array I've used above give a much dark tone of blue. Can't seem the get the it right for some reason.

Any help would be much appreciated. Many thanks!

0

There are 0 answers