Sunday, April 10, 2011

Drawing text with a Gradient

Problem

You want to draw (unicode) text with filled with a gradient.

Solution

Since my middle name is now "Core Graphics", let me help you out. It's actually pretty simple. Create your desired gradient in a your image editor of choice, and save it as a PNG. Import it into your project and then ...

Yep folks thats it. Now if you find that your gradient is slightly out of place, you can use CGContextSetPatternPhase to help. You of course would use this before your drawing statement. The docs say:

The pattern phase is a translation that Quartz applies prior to drawing a pattern in the context. The pattern phase is part of the graphics state of a context, and the default pattern phase is (0,0). Setting the pattern phase has the effect of temporarily changing the pattern matrix of any pattern you draw. For example, setting the context’s pattern phase to (2,3) has the effect of moving the start of pattern cell tiling to the point (2,3) in default user space.

So when all is said and done you get this lovely effect

text drawn with a gradient Best of all this effect works all the back to iOS 2.0!

No comments: