2012-07-31 59 views
6

我有2個屬性字符串說'A'和'。'核心文本 - 字形高度

我需要計算每個字符串的高度。目前返回的高度對於兩者都是相同的,它似乎返回給定字體中最高字符的最大可能高度(即使該字符不存在於字符串中)。

我想獲得這些字符中每個字符的確切像素高度,以便我可以調整它們周圍適合字符(字形)的視圖。我試過使用CTFramesetterSuggestFrameSizeWithConstraints()和CTLineGetTypographicBounds(),但它返回一個類似於屬性字符串大小方法的數字。

希望有關如何去做到這一點的任何提示!

回答

7

到底到了那裏,你可以做這樣的:

// Create an attributed string 
CTLineRef line = CTLineCreateWithAttributedString(_string); 

// Get an array of glyph runs from the line 
CFArrayRef runArray = CTLineGetGlyphRuns(line); 

// loop through each run in the array  
CTRunRef run = .... 

// Get the range of the run   
CFRange range = CFRangeMake... 

// Use CTRunGetImageBounds         
CGRect glyphRect = CTRunGetImageBounds(run, context, range); 

// glyphRect now contains the bounds of the glyph run, if the string is just 1 character you have the correct dimensions of that character.