Re: Drawing text like Lion's Mail
Re: Drawing text like Lion's Mail
- Subject: Re: Drawing text like Lion's Mail
- From: Chase Latta <email@hidden>
- Date: Mon, 08 Aug 2011 15:48:16 -0700
Andre,
I was digging through some old code and found this method I wrote awhile ago. I remember basing this off of a blog post or email thread but I don't remember the original source. I used this for something real quick so the code is not perfect but may be a good starting point to get what you need. Essentially you draw the string into an offscreen bitmap context and then use that to apply a mask. You can then draw a gradient which gives the text a nice gradient. The problem with this code is that it applies the gradient to the entire rect that you are passing so if your text is smaller than your rect you might not get the results you expect; this should be easy to fix though. Note that this is a category on NSString. I hope this helps.
Chase
- (void)drawInRect:(NSRect)rect withAttributes:(NSDictionary *)attributes andGradient:(NSGradient *)gradient;
{
NSMutableDictionary *maskAttrs;
if (attributes != nil)
maskAttrs = [[attributes mutableCopy] autorelease];
else
maskAttrs = [NSMutableDictionary dictionary];
NSRect maskRect = NSMakeRect(0, 0, rect.size.width, rect.size.height);
[maskAttrs setValue:[NSColor whiteColor] forKey:NSForegroundColorAttributeName];
[maskAttrs setValue:[NSColor blackColor] forKey:NSBackgroundColorAttributeName];
CGColorSpaceRef grayScale = CGColorSpaceCreateDeviceGray();
CGContextRef maskContext = CGBitmapContextCreate(NULL, rect.size.width,
rect.size.height, 8, rect.size.width, grayScale, 0);
CGColorSpaceRelease(grayScale);
// Draw the text into an offscreen context
NSGraphicsContext *maskGraphicsContext = [NSGraphicsContext
graphicsContextWithGraphicsPort:maskContext flipped:NO];
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:maskGraphicsContext];
[self drawInRect:maskRect withAttributes:maskAttrs];
[NSGraphicsContext restoreGraphicsState];
CGImageRef alphaMask = CGBitmapContextCreateImage(maskContext);
CGContextRef ctx = [[NSGraphicsContext currentContext] graphicsPort];
// Draw the gradient clipped by the mask of the text
CGContextSaveGState(ctx);
CGContextClipToMask(ctx, NSRectToCGRect(rect), alphaMask);
CGFloat angle = -90;
[gradient drawInRect:rect angle:angle];
CGContextRestoreGState(ctx);
CGImageRelease(alphaMask);
}
> Seems like a lot of work for a simple effect. I may play again with this later on this project. I have save this thread in Mail which is telling me that there's "20 messages selected" using its fancy font effect :-)
>
> Thanks for all infos guys,
>
> Andre Masse
>
_______________________________________________
Cocoa-dev mailing list (email@hidden)
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:
This email sent to email@hidden