如何在文本单元格中设置字体大小,以便字符串填充单元格的rect?

5 cocoa text nstextfieldcell

我有一个包含两个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.width,
                                boundsRect.size.height - monthHeight);
    [dayCell drawWithFrame: dayRect inView: self];

    [[NSColor blackColor] set];
    [NSBezierPath strokeRect: boundsRect];
}
Run Code Online (Sandbox Code Playgroud)

所以我知道我可以询问字符串给定属性需要的大小,我知道我可以让控件改变其大小以适应其内容.这些都不适用:我希望内容(在这种情况下,单元格stringValue)的大小适合已知的rect尺寸,以及实现未知的所需属性.我怎样才能找到所需尺寸?假设我知道我将使用什么字体(因为我这样做).

更新注意:我不想截断字符串,我想增长缩小它,以便整个事物适合,尽可能大的文本大小,提供给提供的矩形.

sga*_*gaw 5

我使用了一些类似的代码,但它处理不同的字体,大小高达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;
}
Run Code Online (Sandbox Code Playgroud)