How to clip a string to a specific width ?
09/07/03 22:47
I need to know where (which character) a string will be clipped to a specific width…
The interesting functions for this problem are supplied by NSLayoutManager: glyphIndexForPoint and characterRangeForGlyphRange.
However using these functions implies the setting of a layout manager and a text container, but the power of the technique is worth the pain…
Then:
unsigned index = [myLayoutManager glyphIndexForPoint:(NSMakePoint(myTargetWidth,2)) inTextContainer: myTextContainer fractionOfDistanceThroughGlyph: nil];
NSRange myRange = [myLayoutManager characterRangeForGlyphRange: NSMakeRange(0,index+1)
actualGlyphRange: nil];
If your objective is to put an ellipse in the middle of the original string, then you will do the job by calling these methods twice, each time with a target width of the (original target width - width of ellipse char) / 2.
The second call should be with a NSMakePoint(myStringWith -myNewTargetWidth,2) to give you the position of the first character of the part of the string going after the ellipse. myStringWith being initialized with the length of the original string…
However using these functions implies the setting of a layout manager and a text container, but the power of the technique is worth the pain…
Then:
unsigned index = [myLayoutManager glyphIndexForPoint:(NSMakePoint(myTargetWidth,2)) inTextContainer: myTextContainer fractionOfDistanceThroughGlyph: nil];
NSRange myRange = [myLayoutManager characterRangeForGlyphRange: NSMakeRange(0,index+1)
actualGlyphRange: nil];
If your objective is to put an ellipse in the middle of the original string, then you will do the job by calling these methods twice, each time with a target width of the (original target width - width of ellipse char) / 2.
The second call should be with a NSMakePoint(myStringWith -myNewTargetWidth,2) to give you the position of the first character of the part of the string going after the ellipse. myStringWith being initialized with the length of the original string…