入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

解决iOS7.0里计算字符串带emoji表情不正确的代码

创建时间:2014-05-23 投稿人: 浏览次数:1396

测试发现iOS7.0里计算带emoji字符串高度时会不正确,而早于7.0版或7.1以上版本都没有这个问题。有使用生成一个label,然后返回label.frame.size.height,但测试发现太耗费性能了。所以写了以下这种方法测试可以


+ (CGFloat)heightWithText:(NSString *)text font:(UIFont *)font constrainedToWidth:(CGFloat)width

{

    // 早于7.0或7.1以上 Christ

    if (kSystemVersionPriorToIOS7||kSystemVersionReachesIOS71) {

       CGSize strSize = [text sizeWithFont:font constrainedToSize:CGSizeMake(width,CGFLOAT_MAX)];

       return ceilf(strSize.height);

    }

    // iOS7.0版本 Christ

   else

    {

        // Get text

        CFMutableAttributedStringRef attrString =CFAttributedStringCreateMutable(kCFAllocatorDefault,0);

        CFAttributedStringReplaceString (attrString,CFRangeMake(0,0), (CFStringRef) text);

       CFIndex stringLength = CFStringGetLength((CFStringRef) attrString);

        

        // Change font

       CTFontRef ctFont = CTFontCreateWithName((__bridge CFStringRef) font.fontName, font.pointSize,NULL);

       CFAttributedStringSetAttribute(attrString, CFRangeMake(0, stringLength), kCTFontAttributeName, ctFont);

        

        // Calc the size

        CTFramesetterRef framesetter =CTFramesetterCreateWithAttributedString(attrString);

       CFRange fitRange;

       CGSize frameSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, stringLength), NULL, CGSizeMake(width, CGFLOAT_MAX), &fitRange);

       CFRelease(ctFont);

       CFRelease(framesetter);

       CFRelease(attrString);

       return frameSize.height;

    }

}

声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
  • 上一篇:没有了
  • 下一篇:没有了
未上传头像