加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

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

发布时间:2020-12-14 21:19:59 所属栏目:资源 来源:网络整理
导读:我有一个包含两个NSTextFieldCells的视图.绘制这些单元格的大小是从视图的大小派生的,我希望每个单元格中的文本最适合单元格的派生大小.这是我的,没有设置字体大小: - (void)drawRect:(NSRect)dirtyRect { /* * Observant readers will notice that I updat
我有一个包含两个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维度,以及实现未知的所需属性.如何找到所需的尺寸?假设我知道我将使用什么字体(因为我这样做).

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

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读