13
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

横幅からWrappedなテキストが納まる領域の高さを求める方法

Posted at

特定の幅の領域に自動折り返しONでテキストを表示する時に、
全体を表示するのに必要な高さを計算する方法。

CATextLayerの必要サイズを求める時などに使ったのでメモ。

func heightForStringDrawing(myString: String, myFont: NSFont, myWidth: CGFloat) -> CGFloat
{
    var textStorage = NSTextStorage(string: myString)
    var textContainer = NSTextContainer(containerSize: NSMakeSize(myWidth, CGFloat(FLT_MAX)))
    var layoutManager = NSLayoutManager()
    layoutManager.addTextContainer(textContainer)
    textStorage.addLayoutManager(layoutManager)
    textStorage.addAttribute(NSFontAttributeName, value:myFont, range:NSMakeRange(0, textStorage.length));
    textContainer.lineFragmentPadding = 0.0
    
    layoutManager.glyphRangeForTextContainer(textContainer)
    return layoutManager.usedRectForTextContainer(textContainer).size.height;
}

Appleが提供してくれててもいい気がしますが
ドキュメントでの紹介しかありません・・・

参考

Calculating Text Height - Mac Developer Library

13
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?