Published in

AndroidPub

# 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.

In this article, as in previous ones, we’ll try to step by step implement one beautiful shot from Dribbble. And today it is a nice Light animation created by Oleg Frolov.

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 LightProgress view’s onDraw method:

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:

1. Calculate text width (w1) with letter “i” (Loadi);
2. Calculate text width (w2) without letter “i” (Load);
3. Calculate one letter “i” width (w3) with font space between letters, w3 = w1 - w2;
4. Calculate pivotX coordinates: pivotX = w1 - w3 / 2;
5. Calculate one letter “i” width (w4) without font space between letters. Here I assume that w4 == diameter of the letter “i” dot;
6. 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.

## Some drawing

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

We use the CustomSpringInterpolator created by Geet Gobind Singh, it suits us well.

• 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 textPaint.

That’s all! A few lines of code, and we have a good loading indicator!

## Examples

You can checkout the source code on GitHub and feel free to fork it 😃

If you liked this article, you may also like my previous articles:

Thank you for reading, Happy Coding!

And don’t forget 👏

--

--

## More from AndroidPub

The (retired) Pub(lication) for Android & Tech, focused on Development