获取 NSTextField 内容以缩放

2024-03-23

我怎样才能让文本比例适合我给它的边界?


我过去也做过类似的事情。

-(void)calcFontSizeToFitRect:(NSRect)r {
    float targetWidth = r.size.width - xMargin;
    float targetHeight = r.size.height - yMargin;
    
    // the strategy is to start with a small font size and go larger until I'm larger than one of the target sizes
    int i;
    for (i=minFontSize; i<maxFontSize; i++) {
        NSDictionary* attrs = [[NSDictionary alloc] initWithObjectsAndKeys:[NSFont fontWithName:currentFontName size:i], NSFontAttributeName, nil];
        NSSize strSize = [stringValue sizeWithAttributes:attrs];
        [attrs release];
        if (strSize.width > targetWidth || strSize.height > targetHeight) break;
    }
    [self setCurrentFontSize:(i-1)];
}

The stringValue变量是您想要调整大小的文本。这xMargin and yMargin变量用于您想要的间距。这minFontSize and maxFontSize变量限制了你想要的大小。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

获取 NSTextField 内容以缩放 的相关文章

随机推荐