android - Apply ColorFilter but preserve transparent shadow in PNG file -


i applying colorfilter drawable wanted know if's possible change color of drawable preserve shadow in it.

something this:

enter image description here

where if applied like:

view.getbackground().setcolorfilter(new porterduffcolorfilter(itemview.getresources().getcolor(r.color.green_500), porterduff.mode.src_in); 

it apply colorfilter preserve shadow , alpha values.

how can achieve this?

i think need hue shifter. if so, using colorfiltergenerator proposed in understanding use of colormatrix , colormatrixcolorfilter modify drawable's hue need do:

view.getbackground().setcolorfilter(colorfiltergenerator.adjusthue(180)); 

the result looks (hue rotated 180 degrees):

enter image description here

note: credit answer must go @richard lalancette awesome answer question linked

update comments:

as need specify target color, can calculate source , target hsv values , use colorfiltergenerator shift hue. example:

// source color (the rgb color original image 255,85,78) float[] hsvsource = new float[3]; color.rgbtohsv(255, 85, 78, hsvsource);  // color hue want achieve (green example) float[] hsvtarget = new float[3]; color.rgbtohsv(0, 200, 18, hsvtarget);  view.getbackground().setcolorfilter(colorfiltergenerator.adjusthue(hsvtarget[0] - hsvsource[0])); 

note approach takes account hue values of colors shift it.

update comments:

@jared rummler's wonderful answer (understanding use of colormatrix , colormatrixcolorfilter modify drawable's hue) takes drawable parameter don't need specify source color:

view.getbackground().setcolorfilter(colorfiltergenerator.from(view.getbackground()).to(color.green)); 

Comments