核心文本.如何计算属性字符串的边界框? [英] CoreText. How Do I Calculate the Bounding Box of an Attributed String?
问题描述
在 CoreText 中,很容易问:对于给定的矩形,这个属性字符串中有多少适合?".
In CoreText it is easy ask: "for a given rectangle how much of this attributed string will fit?".
CTFrameGetVisibleStringRange(rect).length
将返回字符串中下一个文本运行应该开始的位置.
Will return where in the string the next run of text should begin.
我的问题是:给定一个属性字符串和一个宽度,我需要什么矩形高度才能完全绑定属性字符串?".
My question is: "given an attributed string and a width, what rect height do I need to completely bound the attributed string?".
CoreText 框架是否提供工具来执行此操作?
Does the CoreText framework provide tools to do this?
谢谢,
道格
推荐答案
你需要的是 CTFramesetterSuggestFrameSizeWithConstraints()
,你可以这样使用:
What you need is CTFramesetterSuggestFrameSizeWithConstraints()
, you can use it like so:
CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)(attributedString)); /*Create your framesetter based in you NSAttrinbutedString*/
CGFloat widthConstraint = 500; // Your width constraint, using 500 as an example
CGSize suggestedSize = CTFramesetterSuggestFrameSizeWithConstraints(
framesetter, /* Framesetter */
CFRangeMake(0, text.length), /* String range (entire string) */
NULL, /* Frame attributes */
CGSizeMake(widthConstraint, CGFLOAT_MAX), /* Constraints (CGFLOAT_MAX indicates unconstrained) */
NULL /* Gives the range of string that fits into the constraints, doesn't matter in your situation */
);
CGFloat suggestedHeight = suggestedSize.height;
编辑
//IMPORTANT: Release the framesetter, even with ARC enabled!
CFRelease(frameSetter);
因为 ARC 只发布 Objective-C 对象,而 CoreText 处理 C,很可能您会在这里出现内存泄漏.如果你的 NSAttributedString
很小并且你做了一次,你不应该有任何不好的后果.但是如果你有一个循环来计算,比如说,大/复杂 NSAttributedString
s 的 50 个高度,并且你不释放 CTFramesetterRef
,你可以有严重的内存泄漏.查看链接的教程,了解有关内存泄漏和使用仪器调试的更多信息.
As ARC releases only Objective-C objects, and CoreText deals with C, very likely you can have a memory leak here. If your NSAttributedString
is small and you do it once, you shouldn't have any bad consequences. But in a case you have a loop to calculate, let's say, 50 heights of big/complex NSAttributedString
s, and you don't release the CTFramesetterRef
, you can have serious memory leaks. Check the tutorial linked for more information on memory leaks and debugging with instruments.
所以这个问题的解决方法是添加CFRelease(frameSetter);
So the solution for this problem is to add CFRelease(frameSetter);
这篇关于核心文本.如何计算属性字符串的边界框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!