我有一个包含两个NSTextFieldCells的视图.绘制这些单元格的大小是从视图的大小派生的,我希望每个单元格中的文本最适合单元格的派生大小.这是我的,没有设置字体大小:
- - (void)drawRect:(NSRect)dirtyRect {
- /*
- * Observant readers will notice that I update the whole view here. If
- * there is a perceived performance problem,then I'll switch to just
- * updating the dirty rect.
- */
- NSRect boundsRect = self.bounds;
- const CGFloat monthHeight = 0.25 * boundsRect.size.height;
- NSRect monthRect = NSMakeRect(boundsRect.origin.x,boundsRect.origin.y + boundsRect.size.height
- - monthHeight,boundsRect.size.width,monthHeight);
- [monthCell drawWithFrame: monthRect inView: self];
- NSRect dayRect = NSMakeRect(boundsRect.origin.x,boundsRect.origin.y,boundsRect.size.height - monthHeight);
- [dayCell drawWithFrame: dayRect inView: self];
- [[NSColor blackColor] set];
- [NSBezierPath strokeRect: boundsRect];
- }
所以我知道我可以问一个字符串给定属性需要的大小,我知道我可以让控件改变它的大小以适应它的内容.这些都不适用:我希望内容(在这种情况下,单元格的stringValue)的大小适合已知的rect维度,以及实现未知的所需属性.如何找到所需的尺寸?假设我知道我将使用什么字体(因为我这样做).
更新注意:我不想截断字符串,我想增长或缩小它,以便整个事物适合,尽可能大的文本大小,提供给提供的矩形.
@R_301_323@
我使用一些类似的代码,但它处理不同的字体,大小高达10,000,并考虑到可用的高度以及文本显示区域的宽度.
- #define kMaxFontSize 10000
- - (CGFloat)fontSizeForAreaSize:(NSSize)areaSize withString:(NSString *)stringToSize usingFont:(NSString *)fontName;
- {
- NSFont * displayFont = nil;
- NSSize stringSize = NSZeroSize;
- NSMutableDictionary * fontAttributes = [[NSMutableDictionary alloc] init];
- if (areaSize.width == 0.0 || areaSize.height == 0.0) {
- return 0.0;
- }
- NSUInteger fontLoop = 0;
- for (fontLoop = 1; fontLoop <= kMaxFontSize; fontLoop++) {
- displayFont = [[NSFontManager sharedFontManager] convertWeight:YES ofFont:[NSFont fontWithName:fontName size:fontLoop]];
- [fontAttributes setObject:displayFont forKey:NSFontAttributeName];
- stringSize = [stringToSize sizeWithAttributes:fontAttributes];
- if (stringSize.width > areaSize.width)
- break;
- if (stringSize.height > areaSize.height)
- break;
- }
- [fontAttributes release],fontAttributes = nil;
- return (CGFloat)fontLoop - 1.0;
- }