Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Custom Subclass of ColorFilter?

Okay, so this is somewhat related to my previous question on the ColorMatrixColorFilter, but I feel it's a significantly different question. I'm wondering if there's a way - or rather, how to extend the ColorFilter class to create my own custom color filter. For what I'm needing to accomplish, I need to write a custom filter that will query each pixel, convert its RGB value to HSL or LAB, modify the hue, convert it back to RGB, and set that pixel to the new value.

I'm thinking I could simply write a class that does this, taking in a Drawable and an amount of hue shift to perform, but it would have to be called manually for each and every Drawable, and every state of every Drawable, whereas the ColorFilter seems to handle this nicely. Given the existence of the LightingColorFilter and ColorMatrixColorFilter, it seems like it can be subclassed, but so far my efforts to find any sort of documentation have been futile. I can't seem to find the source code for any of the three (Lighting, ColorMatrix, ColorFilter); I'm thinking they're probably done in native code?

My question is this: How can I properly subclass ColorFilter? If I can't find a good answer for that, if anyone is able to find the source (I've searched Android's git) and post a link to that, that would be helpful as well.

Thanks!

like image 283
Kevin Coppock Avatar asked Dec 07 '10 02:12

Kevin Coppock


2 Answers

As you said, the source code shows ColorFilter use native code so you cannot really subclass it.

There's probably no other way than creating your own class for what you want to do.

like image 82
Dalmas Avatar answered Nov 05 '22 18:11

Dalmas


You may use this to apply your own color filter technique unfortunately works on RGB:

// The matrix is stored in a single array, and its treated as follows: [ a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t ]
// When applied to a color [r, g, b, a], the resulting color is computed as (after clamping) ;
//   R' = a*R + b*G + c*B + d*A + e;
//   G' = f*R + g*G + h*B + i*A + j;
//   B' = k*R + l*G + m*B + n*A + o;
//   A' = p*R + q*G + r*B + s*A + t;

Paint paint = new Paint();
float[] matrix = {
        1, 1, 1, 1, 1, //red
        0, 0, 0, 0, 0, //green
        0, 0, 0, 0, 0, //blue
        1, 1, 1, 1, 1 //alpha
};

paint.setColorFilter(new ColorMatrixColorFilter(matrix));

Any way in my case I was needed to apply HSL effect like colorize in PhotoShop it is not 100% correct but this gives nice result :

 float[] HSL = imageLayer.getColorize();
 PorterDuffColorFilter colorFilter = new PorterDuffColorFilter(ColorUtils.HSLToColor(HSL),PorterDuff.Mode.MULTIPLY);
 paint.setColorFilter(colorFilter);
like image 1
Stav Bodik Avatar answered Nov 05 '22 18:11

Stav Bodik