同じ1行のテキストがboundingRectWithSize and
CoreTextメソッドの間で異なる幅になります。ここで iOS boundingRectWithSizeとCoreTextメソッドの間のテキストサイズの計算に関する別の結果
- (IBAction)buttonSeletor:(id)sender {
[self getSeparatedLinesWithText:self.contentField.text fontSize:self.fontField.text.floatValue labelWidth:10000];
}
- (void)getSeparatedLinesWithText:(NSString *)text fontSize:(CGFloat)fontSize labelWidth:(CGFloat)labelWidth
{
UIFont *font = [UIFont systemFontOfSize:fontSize];
CTFontRef myFont = CTFontCreateWithName((__bridge CFStringRef)([font fontName]), [font pointSize], NULL);
NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
CTParagraphStyleSetting set[kCTParagraphStyleSpecifierCount] = { 0 };
int count = 0;
CTLineBreakMode paraLineBreak = (CTLineBreakMode)NSLineBreakByCharWrapping;
set[count].spec = kCTParagraphStyleSpecifierLineBreakMode;
set[count].valueSize = sizeof(CTLineBreakMode);
set[count].value = ¶LineBreak;
count++;
CTParagraphStyleRef style = CTParagraphStyleCreate(set, count);
[attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)myFont range:NSMakeRange(0, attStr.length)];
[attStr addAttribute:(NSString *)kCTParagraphStyleAttributeName value:(__bridge id)style range:NSMakeRange(0, attStr.length)];
CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attStr);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake(0,0,labelWidth,100000));
CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
NSArray *lines = (__bridge NSArray *)CTFrameGetLines(frame);
CGFloat width = [text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName :font} context:nil].size.width;
CTLineRef obj = (__bridge CTLineRef)(lines[0]);
CGRect r = CTLineGetBoundsWithOptions(obj, kCTLineBoundsExcludeTypographicLeading);
NSLog(@"\ntext %@\nboundingRectWithSize %f\nCoreText %f\nboundingRectWithSize/CoreText %f",text,width,r.size.width,width/r.size.width);
}
結果:
デザインスケッチ:あなたは最大3行を表示したい場合は
達成したいことはありますか? – Lion
テキストが長い場合、3行だけが表示されます.Ultabel –
のCoreTextを使用すると、3行の内容が同じ長さではなく、3行の長さになります。テキストを表示するのに何を使用していますか?私はユーラベルを意味する? – Lion