The power of Android Porter/Duff Mode with View Animation
If you read my articles, you probably know that I love Android, beautiful animations and my hobby is to share my experience on Medium. I have got a lot of positive feedback about my previous articles and I am very excited to publish a new one.
It looks very simple but not for developers 😅. Don’t be scared, it’s very easy to implement too. For example this is our custom
Yes, only 3 lines of code! But before, we just need to calculate the angle and prepare drawing paths. Let’s do it step by step.
A “lot” of math
At first we need to find a pivot point for the Light animation (a point around which we will rotate white trapezoid). And as you can see it is the center of the dot of the letter “i”. It’s pretty simple to calculate pivotX and pivotY coordinates:
- Calculate text width (w1) with letter “i” (Loadi);
- Calculate text width (w2) without letter “i” (Load);
- Calculate one letter “i” width (w3) with font space between letters, w3 = w1 - w2;
- Calculate pivotX coordinates: pivotX = w1 - w3 / 2;
- Calculate one letter “i” width (w4) without font space between letters. Here I assume that w4 == diameter of the letter “i” dot;
- Calculate pivotY coordinates: pivotY = (-text.ascent - text.height + w4 / 2) (read more about text ascent, descent, leading etc).
The calculations may seem a bit confusing (especially step 6), in fact it is not, just experiment with the source code.
As you note, I replaced “Light” text with “Loading”. But for another text, the calculation is the same.
For drawing a white Light path we need to calculate a trapezoid (a triangle without a top corner).
let’s light it up
Now all we have to do is start the animation.
- Create an animator object
- Update the angle and invalidate our view
- Start the animation
Not what we really want.
The magic of Android PorterDuff.Mode
As you saw in the
onDraw snippet above, we use a
textPaint to draw a
textBitmap. And to achieve the desired animation, we just need to apply
xfermode to our
That’s all! A few lines of code, and we have a good loading indicator!
You can checkout the source code on GitHub and feel free to fork it 😃
Android implementation of Light animation from Oleg Frolov - bitvale/LightProgress
If you liked this article, you may also like my previous articles:
Thank you for reading, Happy Coding!
And don’t forget 👏