CATextLayer *textLayer = [CATextLayer layer];
textLayer.frame = CGRectMake(80, 0.0f, 36.0f, 18.0f);
textLayer.string = @"12";
textLayer.fontSize = [UIFont systemFontSize];
textLayer.foregroundColor = [UIColor whiteColor].CGColor;
NSLog(@"(width,height)=(%f,%f)",
[textLayer.string sizeWithFont:textLayer.font].width,
[textLayer.string sizeWithFont:textLayer.font].height);
问题是输出总是:(宽度,高度)=(8.000000,0.000000)
答案 0 :(得分:7)
使用sizeWithFont:constrainedToSize:lineBreakMode:
[someString sizeWithFont:yourFont
constrainedToSize:CGSizeMake(maxWidthYouSpecify, CGFLOAT_MAX)
lineBreakMode:UILineBreakModeWordWrap];
答案 1 :(得分:7)
从iOS 7开始,使用NSString
的{{3}}。 boundingRectWithSize:options:attributes:context现已弃用。
CGRect rect = [textLayer.string boundingRectWithSize:textLayer.frame.size options:NSStringDrawingUsesLineFragmentOrigin attributes:nil context:nil];
CGSize size = CGSizeMake(ceilf(rect.size.width), ceilf(rect.size.height));
答案 2 :(得分:1)