【问题标题】:attributed strings with emojis - proper height带有表情符号的属性字符串 - 适当的高度
【发布时间】:2013-11-01 18:02:05
【问题描述】:

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

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

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

【问题讨论】:

  • 你能解决这个问题吗?我有完全相同的问题。
  • 如果你去掉 NSStringDrawingUsesFontLeading 选项,它可能工作得很好,但我想知道 NSStringDrawingUsesFontLeading 到底是做什么来计算高度的

标签: ios nsstring uilabel nsattributedstring emoji


【解决方案1】:

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

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;
}

【讨论】:

  • @Oliver Atkinson:我用过你的代码。它工作正常,但如果文本中有很多空间,那么它就不能正常工作。
  • @bittu 你用的是什么字体?使用系统支持的字体就可以了,我在使用自定义字体时通常会遇到问题
  • 我在系统和自定义(Avenir next)字体中都尝试了这段代码。问题出现在两者中。还有一件事..它适用于两种字体的小文本,但如果文本太大,则不会工作。
  • 我在 swift 中尝试过相同的方法,但 CTFramesetterSuggestFrameSizeWithConstraints() 方法返回零大小,所以@OliverAtkinson 可以告诉它是 swift 版本。
【解决方案2】:
+(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;

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多