Search code examples
androidbackgroundshapestextcolor

Fill shape with text with two different color


I tried to achieve this but I am only able to achieve to fill object (shape). My requirement is to change text color along with shape filling.

Shape can be filled with percentage like till
10% to 50% = Green
51% to 80% = Yellow
81% to 100% = Red

When Yellow color fills background of ":" in shape, it will change color to "White" which is previously "Yellow". Size of this shape is also dynamic.

What I tried and achieved?

I am able to fill shape with percentage but failed to change color when it reaches to edge of text.

enter image description here

enter image description here


Solution

  • I wrote a custom view. You get this double color effect using Path APIs. But for Android 1+ compatibility, you should use Region API and above Kitkat (19+) you can use just Path API.

    Let's go through the concept of how to achieve this effect step by step:

    1. There are three shapes we need to draw - Outline Rounded Stroke + Orange Progress Bar + the text itself
    2. We draw the stroke as it is
    3. But for the Progress bar, we need to remove the text that intersects with it and basically make the text intersection transparent. (DIFFERENCE)
    4. Also for the Progress Bar, we have to show only the part of the rectangle that intersects with the outer rounded stroke path. (INTERSECTION)
    5. And similarly, for the text, on the left side we basically chop off the parts that intersects with the progress bar. And we only show the right side of the text that is orange in color. (DIFFERENCE again)

    If you are using API 19+, this is how the critical code snippet looks like:

    croppedProgressPath.op(progressPath, textPath, Path.Op.DIFFERENCE);
    croppedProgressPath.op(progressStrokePath, Path.Op.INTERSECT);
    ————————————
    croppedTextPath.op(textPath, progressPath, Path.Op.DIFFERENCE);
    

    Lines here and here.

    I’ve written a Proof of Concept for this project called Diffre on Github. If you wanna test it out first, all the code is in this repo.

    Diffre demo gif