您的位置:首页 > 其它

NSString根据宽度获得能显示出的字符串

2017-05-23 21:07 288 查看
- (NSString *)getVisibleStringWithWidth:(CGFloat)width font:(UIFont *)font {

NSMutableParagraphStyle *p = [[NSMutableParagraphStyle alloc] init];

p.lineBreakMode = NSLineBreakByCharWrapping;

NSAttributedString *namesAtt = [[NSAttributedString alloc] initWithString:self attributes:@{NSFontAttributeName:font, NSParagraphStyleAttributeName:p}];

CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)namesAtt);

UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, width, 25.)];

CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, self.length), path.CGPath, NULL);

CFRange range = CTFrameGetVisibleStringRange(frame);

CFRelease(framesetter);

CFRelease(frame);

return [self substringWithRange:NSMakeRange(range.location, range.length)];

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: