8

我正在尝试获取属性字符串的高度。这按预期工作:

[attrString boundingRectWithSize:size
                         options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine)
                         context:NULL]

...除非字符串包含表情符号。使用表情符号,字符串在标签底部被切断。我有什么特别需要做的吗?

4

2 回答 2

3

我知道这是一篇旧文章,但有人可能仍然觉得它有用,您可以转到核心文本并让它为您完成艰苦的工作!

static inline CGSize OKASizeWithAttributedString(NSAttributedString *attributedString, CGFloat width) {

  CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attributedString);
  CGSize targetSize = CGSizeMake(width, CGFLOAT_MAX);
  CGSize size = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, (CFIndex)[attributedString length]), NULL, targetSize, NULL);
  CFRelease(framesetter);

  return size;
}
于 2014-11-21T16:04:00.143 回答
0
+(CGFloat)heightStringWithEmojis:(NSString*)str fontType:(UIFont *)uiFont ForWidth:(CGFloat)width {

    // Get text
    CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
    CFAttributedStringReplaceString (attrString, CFRangeMake(0, 0), (CFStringRef) str );
    CFIndex stringLength = CFStringGetLength((CFStringRef) attrString);

    // Change font
    CTFontRef ctFont = CTFontCreateWithName((__bridge CFStringRef) uiFont.fontName, uiFont.pointSize, NULL);
    CFAttributedStringSetAttribute(attrString, CFRangeMake(0, stringLength), kCTFontAttributeName, ctFont);

    // Calc the size
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attrString);
    CFRange fitRange;
    CGSize frameSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, 0), NULL, CGSizeMake(width, CGFLOAT_MAX), &fitRange);

    CFRelease(ctFont);
    CFRelease(framesetter);
    CFRelease(attrString);

    return frameSize.height;

}
于 2015-03-24T13:08:06.953 回答