On 14 Aug 2012, at 01:30, Ross Carter <rosscarter...@me.com> wrote: > > On Aug 12, 2012, at 5:34 AM, Gerriet M. Denkmann <gerr...@mdenkmann.de> wrote: > >> In windowWillUseStandardFrame:defaultFrame: in a subclass of NSDocument >> (which is also the delegate of it's window) I want to set the window to just >> contain a certain line. >> >> - (NSRect)windowWillUseStandardFrame:(NSWindow *)sender >> defaultFrame:(NSRect)defaultFrame >> { >> // myTextView is an NSTextView inside a scroll view, which is the >> sole window content >> >> NSString *mySpecialLine = @"... something..."; >> NSDictionary *typingAttributes = [ myTextView typingAttributes ]; >> NSFont *typingFont = [ typingAttributes objectForKey: >> NSFontAttributeName ]; >> >> NSSize oneSize = [ mySpecialLine sizeWithAttributes: typingAttributes >> ]; >> // this does not work - it always uses printer fonts even if >> myTextView does not. > > I think the basic problem is in assuming that the Cocoa text system and the > string drawing methods use the same layout. That assumption is not safe. If > you need to know the metrics of a line as it appears in a NSTextView, you > need to ask the NSLayoutManager for the metrics of that specific line > fragment; you cannot ask the attributed string itself, because its > calculations are likely to be different. For one thing, the string drawing > methods might use a different typesetter compatibility setting.
Ok. So I came up with this: - (CGFloat)widthOfTextViewLike: (NSTextView *)oldTextView withLine: (NSString *)fittingLine; { NSDictionary *typingAttributes = [ oldTextView typingAttributes ]; NSFont *typingFont = [ typingAttributes objectForKey: NSFontAttributeName ]; NSLayoutManager *oldLayoutManager = [ oldTextView layoutManager ]; BOOL usesScreenFonts = [ oldLayoutManager usesScreenFonts ]; CGFloat big = 1e4; NSTextView *dummyTextView = [ [ NSTextView alloc ] initWithFrame: NSMakeRect(0,0, big, big) ]; [ dummyTextView setString: fittingLine ]; [ dummyTextView setFont: typingFont ]; [ dummyTextView setMinSize: NSMakeSize(1, big) ]; [ dummyTextView setHorizontallyResizable: YES ]; NSLayoutManager *dummyLayoutManager = [ dummyTextView layoutManager ]; [ dummyLayoutManager setUsesScreenFonts: usesScreenFonts ]; [ dummyTextView sizeToFit ]; NSRect frame = [ dummyTextView frame ]; [ dummyTextView release ]; return frame.size.width; } If there is a better (more efficient) way, please let me know. Kind regards, Gerriet. _______________________________________________ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) 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: https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com