Photo by Francesco Ungaro on Unsplash

Using gradient for styling text

Chris Margonis
Jan 26 · 2 min read

Having an engaging and fancy user interface is essential for providing a delightful user experience. In some cases, this calls for using gradient colors. While Android’s styling system is pretty powerful, it lacks an out-of-the-box way to style a text using a gradient for coloring its text. Since at Plum we always try to explore new ways to achieve the best results, we had to come up with a solution!

CharacterStyle to the rescue!

Thankfully the android.text.style package contains enough tools for extending the already-provided styling capabilities. There’re many ways to extend it, but for this case, we’ll take a look at extending CharacterStyle to match our needs.

The key method of that abstract class is updateDrawState:

This method has as a parameter the TextPaint that will be used in our TextView. Most importantly, the TextPaint can have a shader object for drawing. And for that, we’ll be using LinearGradient shader!

The code

Without further ado, here’s what we came up with:

Using it

The LinearGradientSpan can be used as any other character style:

It’s a relatively easy way to produce an interesting text effect.

Result!

While in a more real scenario (taken from Plum’s android application) the effect can have a more subtle effect:

Closing

As I’m not an expert in Graphics (let alone Android graphics 🤣), there should be plenty of optimizations that this utility class could receive. If you also want to build amazing things (and maybe improve the LinearGradientSpan!) check out our openings!

Making Plum 🛠️

Finance, technology and fruit-based puns.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store