我用 NSAttributedString
s draw(in: rect)
将字符串绘制到 View 中(普通 NSString
也会出现同样的问题)。现在结果似乎与我在 Xcode 中设置的部署目标不同。如果部署目标是 10.13
,绘制调用将其呈现为这样
其中红色框代表rect
.如果我将部署目标切换到 10.14
或以上不触及代码,相同的绘制调用呈现如下
创建一个空项目,设置NSWindow
s 内容 View 类到 TestView
并创建下面的类。
class TestView: NSView {
override func draw(_ dirtyRect: NSRect) {
NSAttributedString(string: "9", attributes: [
.font: NSFont.userFixedPitchFont(ofSize: 48)!,
.foregroundColor: NSColor.labelColor
]).draw(in: bounds)
}
}
现在在 10.13 和 10.14+ 部署目标之间切换,字符串位置将发生变化。如果您要检查字符串 .size()
它返回 68
在 10.13 和 58
在 10.14+ 上。我如何使平台之间保持一致?由于它在一个包内,DT 可能会有所不同,我想避免不同的代码路径。
此外,10.14+ 版本似乎更“正确”。
最佳答案
我尝试更改字体并注意到如果您使用默认系统字体,问题就会消失。这让我相信问题在于固定间距字体——它似乎具有不同的行高,具体取决于 DT。
通过段落样式设置特定的行高可以修复它:
override func draw(_ dirtyRect: NSRect) {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = 58
paragraphStyle.maximumLineHeight = 58
NSAttributedString(string: "9", attributes: [
.font: NSFont.userFixedPitchFont(ofSize: 48)!,
.foregroundColor: NSColor.labelColor,
.paragraphStyle: paragraphStyle
]).draw(in: bounds)
}
关于swift - NSAttributedString 绘制位置在 10.13 和 10.14+ 上不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64233619/