NSString drawInRect overlaps all characters
I am trying to fill some text with a gradient fill, where I set the text drawing mode to crop and then paint the gradient fill. The problem is that whenever I set the text drawing mode for a clip, each character of the text line is placed on top of each other, rather than being colored in sequence to form a word - this is the freakiest!
My code looks like this:
CGRect r = CGRectInset(self.frame, 55, 8);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat components[8] = {44/255, 54/255, 66/255, 1.0
,75/255, 92/255, 111/255, 1.0};
CGFloat locations[2] = {0, 1};
// draw the text gradient fill
CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, 2);
CGContextSetTextDrawingMode(context, kCGTextClip);
[monthString drawInRect:r withFont:f lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentCenter];
CGContextFillRect(context, CGRectMake(0, 0, 320, 20));
source to share
It looks like the UIKit NSString add-ons that allow drawInRect: withFont: etc do not work very well with the kCGTextClip draw mode. I have seen the same behavior and in this answer I provide the code to fill the text with a gradient using pure quartz draw calls. The downside to this approach is that you are limited to the MacRoman text encoding, which lacks support for many Unicode characters.
source to share