Using NSLayoutManager to calculate frames for each

2019-03-24 15:43发布

On this thread, Core Text calculate letter frame in iOS, they were able to calculate the frame of each glyph very precisely using Core Text. The final rects hug the actual drawn glyphs perfectly.

Using NSLayoutManager's boundingRectForGlyphRange:inTextContainer: doesn't seem to return the glyph bounding boxes that precisely:

glyph frames using boundingRectForGlyphRange:inTextContainer

And the returned rects don't fully enclose more complex fonts (Zapfino example):

Zapfino f glyph using boundingRectForGlyphRange:inTextContainer

Does anyone know how to replicate the results from the above mentioned discussion without going into Core Text under iOS 7 only apps?

Thanks.

2条回答
唯我独甜
2楼-- · 2019-03-24 16:00

The selected answer in the post you link to apparently solves this problem for Zapfino.

查看更多
唯我独甜
3楼-- · 2019-03-24 16:05

I've found a solution for this issue or at least sort of

Problem: boundingRectForGlyphRange results is off in case of RTL text.

So in case of RTL text is detected only:

Using NSLayoutManager method locationForGlyphAtIndex, for each letter in the range. These are the starting points of each glyph in the range. Using these points I adjust the boundingRect correctly.

Here is an outline of it:

CGPoint endPoint = ((NSValue *)pointsOfGlyps.firstObject).CGPointValue;
CGPoint startPoint = ((NSValue *)pointsOfGlyps.lastObject).CGPointValue;
boundingRect.origin.x =  startPoint.x;
boundingRect.size.width = endPoint.x - startPoint.x + letterWidth;

letterWidth is an approximation of a letter width calculated as the delta between two consecutive starting points.

查看更多
登录 后发表回答