简体   繁体   中英

How do I apply a PorterDuff filter to text color?

I don't want to use a state selector. I want to write generic code to apply a filter to a text color, no matter what the original color might be.

This is actually part of tinting buttons when pressed. I've learned that I can tint an ImageButton easily:

imageButton.setColorFilter(Color.argb(150, 155, 155, 155));

For a Button, I can tint the background image:

button.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);

However, I'm having trouble figuring out how to tint the color value for the text of the Button. Any ideas? Is there some method somewhere so I can apply a PorterDuff tint to an arbitrary color value, so I can set the new value as the tet color?

I spent hours studying documentation and forums and can find absolutely no direct way to apply a PorterDuff filter to text or an arbitrary (int) color value; everything seems to relate to images.

My workaround is ugly, but the only solution I have found:

int normalTextColor = Color.argb(0, 155, 155, 155);
Bitmap bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); //make a 1-pixel Bitmap
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(normalTextColor); //color we want to apply filter to
canvas.drawColor(pressedFilterColor, mode); //apply filter
int pressedTextColor = bitmap.getPixel(0,  0);

Presto--now you can use setColor() or setTextColor() with the new pressedTextColor on your TextView, Button, etc.

I would love to hear of an alternative that doesn't involve drawing a one-pixel Bitmap, as that seems rather ridiculous--but this does get the job done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM