简体   繁体   中英

boundingRectForGlyphRange always returns rect for font size 12

I am trying to calculate the rects of individual glyphs using boundingRectForGlyphRange method. Everything works well except it always returns the rect as if the font size was 12. Event though I set it to 20 in attributed string.

let font = UIFont.systemFontOfSize(20)
var attributedString = NSMutableAttributedString(string: text)
let range = NSRange(location: 0, length: countElements(text))
attributedString.addAttribute(NSFontAttributeName, value: font, range: range)


let textContainer = NSTextContainer()
textContainer.size = CGSize(width: 300, height: 100)
let layoutManager = NSLayoutManager()
let textStorage = NSTextStorage(string: attributedString.mutableString)

layoutManager.textStorage = textStorage
layoutManager.addTextContainer(textContainer)

let rect = layoutManager.boundingRectForGlyphRange(NSRange(location: 0, length: 1), inTextContainer: textContainer)

How do I make it return rect for text size 20 instead of 12?

Just initialise NSTextStorage with attributedString: .

let textStorage = NSTextStorage(attributedString: attributedString)

instead of

let textStorage = NSTextStorage(string: attributedString.mutableString)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM