Created
June 5, 2012 03:25
-
-
Save odrobnik/2872435 to your computer and use it in GitHub Desktop.
Inner Shadow on Label
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (void)drawTextInRect:(CGRect)rect | |
{ | |
[super drawTextInRect:rect]; | |
CGContextRef ctx = UIGraphicsGetCurrentContext(); | |
NSString *fontName = self.font.fontName; | |
CGFloat fontSize = self.font.pointSize; | |
CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)fontName, fontSize, NULL); | |
int charCount = [self.text length]; | |
CGGlyph glyphs[charCount]; | |
CGRect rects[charCount]; | |
CGSize advances[charCount]; | |
CTFontGetGlyphsForCharacters(font, (const unichar*)[self.text cStringUsingEncoding:NSUnicodeStringEncoding], glyphs, charCount); | |
CTFontGetAdvancesForGlyphs(font, kCTFontDefaultOrientation, glyphs, advances, charCount); | |
CTFontGetBoundingRectsForGlyphs(font, kCTFontDefaultOrientation, glyphs, rects, charCount); | |
CGMutablePathRef glyphPath = CGPathCreateMutable(); | |
int totalwidth = 0, maxheight = 0; | |
CGPoint textPosition = CGPointZero; | |
CGFloat ascent = CTFontGetAscent(font); | |
for (int i=0; i < charCount; i++) | |
{ | |
totalwidth += rects[i].size.width; | |
maxheight = maxheight < rects[i].size.height ? rects[i].size.height : maxheight; | |
CGPathRef oneGlyphPath = CTFontCreatePathForGlyph(font, glyphs[i], NULL); | |
CGAffineTransform offsetTransform = CGAffineTransformMake(1, 0, 0, 1, textPosition.x, self.bounds.size.height - ascent); | |
CGPathAddPath(glyphPath, &offsetTransform, oneGlyphPath); | |
textPosition.x += advances[i].width; | |
textPosition.y += advances[i].height; | |
} | |
CGPathRef innerpath = CGPathCreateCopy(glyphPath); | |
// adding a rect around the inner path inverts it with EOF fill rule | |
CGPathAddRect(glyphPath, NULL, self.bounds); | |
// flip the coordinate system | |
CGContextSetTextMatrix(ctx, CGAffineTransformIdentity); | |
CGContextTranslateCTM(ctx, 0, self.bounds.size.height); | |
CGContextScaleCTM(ctx, 1.0, -1.0); | |
CGContextAddPath(ctx, innerpath); | |
CGContextClip(ctx); | |
[[UIColor blueColor] set]; | |
CGContextFillRect(ctx, self.bounds); | |
CGContextAddPath(ctx, glyphPath); | |
CGColorRef color = [UIColor colorWithWhite:0 alpha:0.8].CGColor; | |
CGContextSetShadowWithColor(ctx, CGSizeMake(3, 3), 4, color); | |
CGContextEOFillPath(ctx); | |
CGPathRelease(glyphPath); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment