tôi đã kết thúc làm điều này:
textlayer
là một CATextlayer
theString
là một NSMutableAttributedString
Và vâng, nó không phải rất thanh lịch và chắc chắn có thể được cải thiện;)
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)theString);
CGRect columnRect = CGRectMake(0, 0 , 320, 150);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, columnRect);
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);
CFRange frameRange = CTFrameGetVisibleStringRange(frame);
int fontSize = 18;
while(theString.string.length > frameRange.length){
fontSize--;
CFStringRef fontName = (__bridge CFStringRef)[defs objectForKey:@"font"];
CTFontRef font = CTFontCreateWithName(fontName, fontSize, NULL);
[theString addAttribute:(NSString *)kCTFontAttributeName
value:(__bridge id)font
range:NSMakeRange(0, theString.string.length)];
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)theString);
CGRect columnRect = CGRectMake(0, 0 , 320, 150);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, columnRect);
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);
frameRange = CTFrameGetVisibleStringRange(frame);
textLayer.string = theString;
}
Khi bạn nói 'text của một chiều dài chưa biết', bạn có nghĩa là không biết đến tại thời gian biên dịch? Tại một số thời điểm, bạn * phải * biết chiều dài ... – nall
Haha - ok, điểm tốt. Đó là văn bản được người dùng nhập vào tại một thời điểm nào đó. Tất nhiên, tôi có thể nhận được chuỗi dài ... :) – Swissdude