2017-10-09 62 views
0
的*實際*高度

我創建了一個簡單的CFAttributedString與富利粗體字體和大小100px的:如何獲得CFAttributedString

let font = NSFont(name: "Futura-Bold", size: 100.0)!

當我呈現在CGContext(與CTFramesetterCreateFrame),該字符串我得到的下面的圖片:

enter image description here

現在的問題是如何得到真正高度本書的?正如你可以看到上面的例子,我們正在看85px。

當查詢各種屬性,我得到以下值font對象:

font.pointSize // 100.0 
font.ascender // 103.90 
font.descender // -25.99 
font.capHeight // 75.40 
font.leading // 2.99 
font.boundingRectForFont // (-22.7, -34.3994140625, 168.6, 144.29931640625) 

有誰知道計算渲染字符串的實際像素大小?

回答

3

一個解決方案,爲您提供您所尋求的價值是使用NSString boundingRect(with:options:attributes:)方法。通過傳遞正確的選項,你得到期望的結果:

let font = NSFont(name: "Futura-Bold", size: 100)! 
let text: NSString = "Hello World!" 
let rect = text.boundingRect(with: NSSize(width: 0, height: 0), options: [ .usesDeviceMetrics ], attributes: [ .font: font ], context: nil) 
print("Height of \"\(text)\" is \(rect.height)") 

輸出: 「Hello World」 的

的高度是85.1

這也適用於NSAttributedString

let font = NSFont(name: "Futura-Bold", size: 100)! 
let attrStr = NSAttributedString(string: "Hello World!", attributes: [ .font: font ]) 
let rect2 = attrStr.boundingRect(with: NSSize(width: 0, height: 0), options: [ .usesDeviceMetrics ]) 
print("Height of \"\(attrStr)\" is \(rect2.height)") 

輸出: 「你好!世界{
NSFont = 」

的高度\「。富利粗體100.00 PT P [](0x7ff6eae563b0)fobj = 0x7ff6eaf1ea50,SPC = 34.00 \」 「
}」 是85.1

如果需要的話,你可以抹上CFAttributedStringNSAttributedString

let attrStr: CFAttributedString = ... // some CFAttributedString 
let rect2 = (attrStr as NSAttributedString).boundingRect(with: NSSize(width: 0, height: 0), options: [ .usesDeviceMetrics ]) 
+0

謝謝rmaddy。這工作完美無瑕。 – Pono

1

除了rmaddys的出色答卷,我發現我自己多了一個解決方案,它也給了想要的結果。訣竅是使用CTLineGetImageBounds

let font = NSFont(name: "Futura-Bold", size: 100.0)! 
let text = NSAttributedString(string: "Hello World!", attributes: [.font:font]) 
let line = CTLineCreateWithAttributedString(text) 

print(CTLineGetImageBounds(line, textContext)) 

其中textContext是在其上渲染你的文字一個CGContext上。每蘋果文檔:

這是必需的,因爲上下文可能有它的設置, 會導致圖像邊界的變化。

上面的代碼提供了以下結果:

(7.9, -2.1, 664.2, 85.1) 
        ^^^^