Advertisement
trss

Visible bounds of text in Cocoa

Sep 21st, 2012
1,116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. - (void)drawRect:(NSRect)dirtyRect
  2. {
  3.     NSFont *font = [NSFont fontWithName:@"Zapfino" size:40.0];
  4.     NSAttributedString *string = [[NSAttributedString alloc] initWithString:@"flapfino\ntest" attributes:[NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName]];
  5.    
  6.     NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:string];
  7.     NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
  8.     NSTextContainer *textContainer = [[NSTextContainer alloc] initWithContainerSize:NSMakeSize(FLT_MAX, FLT_MAX)];
  9.     [layoutManager addTextContainer:textContainer];
  10.     [textStorage addLayoutManager:layoutManager];
  11.    
  12.     NSUInteger numGlyphs = [layoutManager numberOfGlyphs];
  13.     NSRange glyphRange = NSMakeRange(0, numGlyphs);
  14.  
  15.     NSRect visibleBounds = NSZeroRect;
  16.     for (NSUInteger i = glyphRange.location; i < glyphRange.location + glyphRange.length; ++i) {
  17.         NSPoint offsetForGlyph = [layoutManager locationForGlyphAtIndex:i];
  18.         offsetForGlyph.y += NSMinY([layoutManager lineFragmentRectForGlyphAtIndex:i effectiveRange:NULL]);
  19.         NSRect boundingRectForGlyph = [[textStorage font] boundingRectForGlyph:[layoutManager glyphAtIndex:i]];
  20.         if ([self isFlipped])
  21.             boundingRectForGlyph.origin.y = - NSMinY(boundingRectForGlyph) - NSHeight(boundingRectForGlyph);
  22.         visibleBounds = NSUnionRect(visibleBounds, NSOffsetRect(boundingRectForGlyph, offsetForGlyph.x, offsetForGlyph.y));
  23.     }
  24.    
  25.     NSRect viewBounds = [self bounds];
  26.     NSPoint offsetForCentering = NSMakePoint(NSWidth(viewBounds) / 2 - NSWidth(visibleBounds) / 2 - NSMinX(visibleBounds), NSHeight(viewBounds) / 2 - NSHeight(visibleBounds) / 2 - NSMinY(visibleBounds));
  27.    
  28.     [layoutManager drawGlyphsForGlyphRange:glyphRange atPoint:offsetForCentering];
  29.    
  30.     NSRect typographicBounds = [layoutManager usedRectForTextContainer:textContainer];
  31.     [[NSBezierPath bezierPathWithRect:NSOffsetRect(typographicBounds, offsetForCentering.x, offsetForCentering.y)] stroke];
  32.    
  33.     [[NSBezierPath bezierPathWithRect:NSOffsetRect(visibleBounds, offsetForCentering.x, offsetForCentering.y)] stroke];
  34. }
  35.  
  36. - (BOOL)isFlipped
  37. {
  38.     return YES;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement