The method I use goes like this:

   1. Create a CGContext (maskContext);
   2. Draw the original text into maskContext;
   3. Create another CGContext (gradientContext);
   4. Use CGContextClipToMask() to mask gradientContext using the CGImage
generated from CGBitmapContextCreateImage(maskContext);
   5. Draw gradient into gradientContext;
   6. Generate a CGImage from the gradientContext, and draw this image in
place of the original text.

I like this technique because you can easily override any text-drawing
method to have it draw the exact same text but with a gradient applied. For
example, I use it to apply a gradient to the text of a custom button, by
creating an NSButtonCell subclass, and overriding the
-drawTitle:withFrame:inView: method like so:

- (NSRect)drawTitle: (NSAttributedString *)title withFrame: (NSRect)frame
inView: (NSView *)view
{
   [ALDrawGradientShadowText prepareWithRect: frameBounds gradient: gradient
shadow: shadow];
   NSRect result = [super drawTitle: title withFrame: frame inView: view];
   [ALDrawGradientShadowText finish];
   return result;
}

Where ALDrawGradientShadowText implements the steps listed above.
(+prepareWithRect:gradient:shadow: implements step 1 and remembers its
state, and +finish implements steps 3-6, and actually draws the resulting
gradient text.)

And you could of course do the exact same with NSAttributedString's various
draw methods.
_______________________________________________

Cocoa-dev mailing list ([email protected])

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [email protected]

Reply via email to