gpt4 book ai didi

cocoa - 如何以最佳方式将 NSString 放入矩形中?

转载 作者:行者123 更新时间:2023-12-03 16:44:37 25 4
gpt4 key购买 nike

Possible Duplicate:
Change NSTextField font size to fit

我试图将一个可变长度的字符串(字符串中的单词数未知)放入给定的矩形内。我想优化字符串的大小,使其尽可能大并适合矩形。此外,如果有多个单词,则字符串应自动换行,并且一个单词不应部分呈现在多行上。我的问题是有时一个单词部分地分布在多行上,如下所示。关于我可能做错了什么有什么建议吗?

谢谢。

alt text

我正在使用 NSLayoutManager、NSTextStorage 和 NSTextContainer。

我按如下方式初始化所有内容:

    textStorage = [[NSTextStorage alloc] initWithString:@""];
layoutManager = [[NSLayoutManager alloc] init];
textContainer = [[NSTextContainer alloc] init];

[layoutManager addTextContainer:textContainer];
[textStorage addLayoutManager:layoutManager];

paraStyle = [[NSMutableParagraphStyle alloc] init];
[paraStyle setLineBreakMode:NSLineBreakByWordWrapping];
[paraStyle setParagraphStyle:[NSParagraphStyle defaultParagraphStyle]];
[paraStyle setAlignment:NSCenterTextAlignment];

然后我按如下方式计算字体大小,

- (float)calculateFontSizeForString:(NSString *)aString andBoxSize:(NSSize)aBox
{
//Create the attributed string
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:aString];
[textStorage setAttributedString:attrString];
[textContainer setContainerSize:NSMakeSize(aBox.width, FLT_MAX)];
[attrString release]; //Clean up

//Initial values
float fontSize = 50.0;
float fontStepSize = 100.0;
NSRect stringRect;
BOOL didFindHeight = NO;
BOOL shouldIncreaseHeight = YES;

while (!didFindHeight)
{
NSMutableDictionary *stringAttributes = [NSMutableDictionary dictionaryWithObjectsAndKeys:
paraStyle, NSParagraphStyleAttributeName,
[NSFont systemFontOfSize:fontSize], NSFontAttributeName, nil];

[textStorage addAttributes:stringAttributes range:NSMakeRange(0, [textStorage length])];

(void)[layoutManager glyphRangeForTextContainer:textContainer];
stringRect = [layoutManager usedRectForTextContainer:textContainer];

if (shouldIncreaseHeight)
{
if (stringRect.size.height > aBox.height)
{
shouldIncreaseHeight = NO;
fontStepSize = fontStepSize/2;
}

fontSize += fontStepSize;
}
else
{
if (stringRect.size.height < aBox.height)
{
shouldIncreaseHeight = YES;

fontStepSize = fontStepSize/2;

if (fontStepSize <= 0.5)
{
didFindHeight = YES;
}
}

if ((fontSize - fontStepSize) <= 0)
{
fontStepSize = fontStepSize/2;
}
else
{
fontSize -= fontStepSize;
}
}
}

return fontSize;
}

最佳答案

发帖前请先搜索。这会反复出现。最新答案是here ,但我认为其他地方有更完整的答案和代码 list 。

我承认简单的示例展示了如何在没有文本容器和布局管理器的情况下完成此操作,但您的方法更强大。不幸的是,蛮力(缩小尺寸直到合适)是确定最合适的唯一方法。

关于cocoa - 如何以最佳方式将 NSString 放入矩形中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4550622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com