#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
本文介绍了一个Objective-C类StringHeight,该类提供了一个静态方法用于计算指定文本的高度,适用于给定宽度约束的情况。通过使用Core Text框架,该方法能够准确地测量文本在iOS或macOS应用中的实际高度。
8584

被折叠的 条评论
为什么被折叠?



