2010-05-25 25 views

回答

19

我以前做过这样的事情。

-(void)calcFontSizeToFitRect:(NSRect)r { 
    float targetWidth = r.size.width - xMargin; 
    float targetHeight = r.size.height - yMargin; 

    // the strategy is to start with a small font size and go larger until I'm larger than one of the target sizes 
    int i; 
    for (i=minFontSize; i<maxFontSize; i++) { 
     NSDictionary* attrs = [[NSDictionary alloc] initWithObjectsAndKeys:[NSFont fontWithName:currentFontName size:i], NSFontAttributeName, nil]; 
     NSSize strSize = [string sizeWithAttributes:attrs]; 
     [attrs release]; 
     if (strSize.width > targetWidth || strSize.height > targetHeight) break; 
    } 
    [self setCurrentFontSize:(i-1)]; 
} 

字符串变量是您想调整大小的文本。 xMargin和yMargin变量用于您想要的间距。 minFontSize和maxFontSize变量会限制您想要的大小。

+0

哇。太棒了!感谢一堆!!!!!! – 2010-05-26 20:06:32

+0

刚刚发现这个,它帮助了我一堆,谢谢! – 2011-03-18 04:36:54

+1

这对多行文本字段不适用。 – 2011-04-05 13:57:56