Hi,
I'm trying to manually trim and add an ellipsis to a string and in order to do this I must find the text that fits inside a rectangle. From what I've read, using CoreText CTFrameGetVisibleStringRange is the correct way, however, when I'm using a custom font, the visible range is one line shorter than it should be. Here's an example where I measure the text with boundingRectWithSize and feed it to a CTFrame. For some reason, the last line is not considered visible.
let string = NSAttributedString(string:"Un loremips sum «lorem ipsum loremips», lore mipsumlo rem loremipsum loremipsumlor da lo remipsuml de thefinalwordlor", attributes:[NSFontAttributeName:UIFont(name:"Avenir-Medium", size:18)!])
let measure = string.boundingRect(with:CGSize(width:270, height:CGFloat.greatestFiniteMagnitude), options:.usesLineFragmentOrigin, context:nil)
let size = CGSize(
width: ceil(measure.width),
height: ceil(measure.height)
)
let label = UILabel(frame:.zero)
label.frame = CGRect(origin:CGPoint(x:64, y:64), size:size)
label.numberOfLines = 0
label.layer.borderWidth = 1
label.layer.borderColor = UIColor.blue.cgColor
self.view.addSubview(label)
let framesetter = CTFramesetterCreateWithAttributedString(string as CFAttributedString)
let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), CGPath(rect:CGRect(origin:.zero, size:size), transform:nil), nil)
let range = CTFrameGetVisibleStringRange(frame)
let text = string.attributedSubstring(from:NSMakeRange(range.location, range.length))
label.attributedText = text
Hopefully I'm missing something. In that specific case, I found that if I add 1 pixel to the frame height, the last line is included correctly. However, I'm guessing this "magical" 1px value might be 2 px if the font is bigger or the line height different therefore I can't fix it like this. Anyone knows what's happening ?
Thanks