How do I set the font size in a text cell so that the string fills the cell's rect?

后端 未结 6 1366
刺人心
刺人心 2020-12-30 15:13

I have a view that contains two NSTextFieldCells. The size at which these cells are drawn is derived from the size of the view, and I want the text in each cell

6条回答
  •  再見小時候
    2020-12-30 16:10

    I use some similar code but it handles different fonts, sizes up to 10,000 and takes into account the available height as well as width of the area the text is being displayed in.

    #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;
    }
    

提交回复
热议问题