用emojis归因字符串 - 适当的高度

时间:2013-11-01 18:02:06

标签: ios nsstring uilabel nsattributedstring emoji

我正在尝试获取属性字符串的高度。这正如预期的那样:

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

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

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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;

}