gpt4 book ai didi

macos - NSLayoutManager/NSTextContainer 忽略比例因子

转载 作者:行者123 更新时间:2023-12-03 17:19:28 33 4
gpt4 key购买 nike

我正在尝试使用以下方法在给定恒定宽度的情况下测量 NSAttributedString 的高度:

-(CGFloat)calculateHeightForAttributedString:(NSAttributedString*)attributedNotes {
CGFloat scrollerWidth = [NSScroller scrollerWidthForControlSize:NSRegularControlSize scrollerStyle:NSScrollerStyleLegacy];
CGFloat width = self.tableView.frame.size.width - self.cellNotesWidthConstraint - scrollerWidth;
// http://www.cocoabuilder.com/archive/cocoa/54083-height-of-string-with-fixed-width-and-given-font.html
NSTextView *tv = [[NSTextView alloc] initWithFrame:NSMakeRect(0, 0, width - 20, 1e7)];
tv.font = [NSFont userFontOfSize:32];
[tv.textStorage setAttributedString:attributedNotes];
[self setScaleFactor:[self convertSliderValueToFontScale:self.fontScaleSlider] forTextView:tv];

[tv.layoutManager glyphRangeForTextContainer:tv.textContainer];
[tv.layoutManager ensureLayoutForTextContainer:tv.textContainer];

return [tv.layoutManager usedRectForTextContainer:tv.textContainer].size.height + 10.0f; // add a little bit of a buffer
}

基本上,宽度是表格 View 的大小减去滚动条和用于显示其他信息的每个单元格的一点点。只要文本比例(通过 convertSliderValueToFontScale:)为 1.0,此方法就非常有效。但是,如果我更改比例因子,usedRectForTextContainer 的结果将不正确 - 就好像未考虑比例因子一样。

在 NSTextView 上的 setScaleFactor:forTextView: 中设置比例,如下(标量是实际比例量):

[textView scaleUnitSquareToSize:NSMakeSize(scaler, scaler)];

关于如何解决这个问题有什么想法吗?

编辑:我有一个示例项目可以在这里尝试:Github 。奇怪的是,如果比例 < 0,事情就会起作用,并且有时它们似乎随机在 4.XXX 范围内起作用......

最佳答案

答案很简单:将 NSTextView 添加为 NSClipView 的 subview ,并与 NSTextView 具有相同的框架。

最终的高度函数如下:

-(CGFloat)calculateHeightForAttributedString:(NSAttributedString*)attributedNotes {
CGFloat width = self.textView.frame.size.width;
// http://www.cocoabuilder.com/archive/cocoa/54083-height-of-string-with-fixed-width-and-given-font.html
NSTextView *tv = [[NSTextView alloc] initWithFrame:NSMakeRect(0, 0, width, 1e7)];
tv.horizontallyResizable = NO;
tv.font = [NSFont userFontOfSize:32];
tv.alignment = NSTextAlignmentLeft;
[tv.textStorage setAttributedString:attributedNotes];
[self setScaleFactor:self.slider.floatValue forTextView:tv];

// In order for usedRectForTextContainer: to be accurate with a scale, you MUST
// set the NSTextView as a subview of an NSClipView!
NSClipView *clipView = [[NSClipView alloc] initWithFrame:NSMakeRect(0, 0, width, 1e7)];
[clipView addSubview:tv];

[tv.layoutManager glyphRangeForTextContainer:tv.textContainer];
[tv.layoutManager ensureLayoutForTextContainer:tv.textContainer];
return [tv.layoutManager usedRectForTextContainer:tv.textContainer].size.height;
}

关于macos - NSLayoutManager/NSTextContainer 忽略比例因子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39087754/

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