gpt4 book ai didi

swift - 在 NSView 中编写

转载 作者:搜寻专家 更新时间:2023-11-01 06:03:28 26 4
gpt4 key购买 nike

我正在尝试在 NSView Canvas 中呈现文本。我需要写三行文字,忽略其他内容。带有提供的矩形的 String.draw(in:withAttributes) 看起来很完美。我的代码如下所示:

func renderText(_ string:String, x:Double, y:Double, numberOfLines: Int, withColor color:Color) -> Double {
let font = NSFont.boldSystemFont(ofSize: 11)
let lineHeight = Double(font.ascender + abs(font.descender) + font.leading)
let textHeight = lineHeight * Double(numberOfLines) + font.leading // three lines
let textRect = NSRect(x: x, y: y, width: 190, height: textHeight)
string.draw(in: textRect, withAttributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: color])
return textHeight
}

renderText("Lorem ipsum...", x: 100, y: 100, numberOfLines: 3, withColor: NSColor.white)

没有调整,我只得到两行文本:

enter image description here

我遵循以下准则:https://developer.apple.com/library/content/documentation/TextFonts/Conceptual/CocoaTextArchitecture/FontHandling/FontHandling.html#//apple_ref/doc/uid/TP40009459-CH5-SW18

我错过了什么?

最佳答案

最终,通过调用构成 Cocoa 文本架构的类,您的文本会出现在屏幕上,因此直接从这些类中获取有关行高的信息是有意义的。在下面的代码中,我创建了一个 NSLayoutManager 实例,并将其排版器行为属性设置为与函数 drawInRect:withAttributes 创建的机器最终使用的排版器的值相匹配: 。然后调用布局管理器的 defaultLineHeight 方法为您提供所需的高度值。

lazy var layoutManager: NSLayoutManager = {
var layoutManager = NSLayoutManager()
layoutManager.typesetterBehavior = .behavior_10_2_WithCompatibility
return layoutManager
}()

func renderText(_ string:String, x:Double, y:Double, numberOfLines: Int, withColor color:NSColor) -> Double {
let font = NSFont.boldSystemFont(ofSize: 11)
let textHeight = Double(layoutManager.defaultLineHeight(for: font)) * Double(numberOfLines)
let textRect = NSRect(x: x, y: y, width: 190, height: textHeight)
string.draw(in: textRect, withAttributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: color])
return textHeight
}

关于swift - 在 NSView 中编写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43763686/

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