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

后端 未结 6 1343
刺人心
刺人心 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:05

    Here is a method that does not do guess and check. Depending on the font, a little padding may be necessary to prevent overflow (sizeWithAttributes doesn't scale perfectly). Boom!

    -(float)scaleToAspectFit:(CGSize)source into:(CGSize)into padding:(float)padding
    {
        return MIN((into.width-padding) / source.width, (into.height-padding) / source.height);
    }
    
    -(NSFont*)fontSizedForAreaSize:(NSSize)size withString:(NSString*)string usingFont:(NSFont*)font;
    {
        NSFont* sampleFont = [NSFont fontWithDescriptor:font.fontDescriptor size:12.];//use standard size to prevent error accrual
        CGSize sampleSize = [string sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:sampleFont, NSFontAttributeName, nil]];
        float scale = [self scaleToAspectFit:sampleSize into:size padding:10];
        return [NSFont fontWithDescriptor:font.fontDescriptor size:scale * sampleFont.pointSize];
    }
    

提交回复
热议问题