您的位置:首页 > 移动开发 > IOS开发

iOS 计算字符串的高度类

2015-08-04 11:25 615 查看
#import <Foundation/Foundation.h>

@interface StringHeight :
NSObject
+ (CGFloat)heightWithText:(NSString *)text font:(UIFont *)font constrainedToWidth:(CGFloat)width;

@end

#import "StringHeight.h"

#import <CoreText/CoreText.h>

@implementation StringHeight

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

    
   
if (!text) {

        
       
return 0.0;
    }

    // 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);

    //NSLog(@"frameSize=======:%f", frameSize.height);
   
return frameSize.height;
}

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