我有一个自定义 UIView 正在通过 CoreText 绘制一个 NSString :
- (NSMutableAttributedString *)getAttributedString : (NSString *)displayText {
string = [[NSMutableAttributedString alloc]
initWithString:displayText];
helvetica = CTFontCreateWithName(CFSTR("Helvetica"), 20.0, NULL);
[string addAttribute:(id)kCTFontAttributeName
value:(__bridge id)helvetica
range:NSMakeRange(0, [string length])];
return string;
}
- (void)drawRect:(CGRect)rect
{
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(
(__bridge CFAttributedStringRef)string);
// left column form
leftColumnPath = CGPathCreateMutable();
CGPathAddRect(leftColumnPath, NULL,
CGRectMake(0, 0,
self.bounds.size.width,
self.bounds.size.height));
// left column frame
textleftFrame = CTFramesetterCreateFrame(framesetter,
CFRangeMake(0, 0),
leftColumnPath, NULL);
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
// right column form
rightColumnPath = CGPathCreateMutable();
CGPathAddRect(rightColumnPath, NULL,
CGRectMake(self.bounds.size.width/2.0, 0,
self.bounds.size.width/2.0,
self.bounds.size.height));
NSInteger rightColumStart = CTFrameGetVisibleStringRange(textleftFrame).length;
// right column frame
textrightFrame = CTFramesetterCreateFrame(framesetter,
CFRangeMake(rightColumStart, 0),
rightColumnPath,
NULL);
}
// flip the coordinate system
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
// draw
CTFrameDraw(textleftFrame, context);
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
CTFrameDraw(textrightFrame, context);
}
// cleanup
CFRelease(textleftFrame);
CGPathRelease(leftColumnPath);
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
CFRelease(textrightFrame);
CGPathRelease(rightColumnPath);
}
CFRelease(framesetter);
CFRelease(helvetica);
CFRelease(helveticaBold);
}
在另一个类中,我尝试使用 boundingRectWithSize 来计算视图显示文本的时间(然后我设置一个 UIScrollView 来匹配这个):
NSMutableAttributedString * attributedString = [textView getAttributedString:text];
// Code here for iOS 7.0 - sizeWithFont is deprecated.
CGRect textBoxSize = [attributedString boundingRectWithSize:CGSizeMake(315.f, CGFLOAT_MAX) options: (NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) context:nil];
textView.frame = CGRectMake(textView.frame.origin.x, pictureSpace, textBoxSize.size.width, textBoxSize.size.height);
getAttributedString 方法在上面。问题是 textView 的高度稍微太短了,因此切断了 so 文本的最后一行。谁能提出什么问题?
另外,附带说明一下,为什么 boundingRectWithSize 中的大小必须为 315(即比屏幕宽度略短)而不是 320 才能工作?在 320 处,textView 最终对于屏幕来说有点太宽了。
编辑 - 这似乎只发生在某些字体上 - 例如 Verdana 工作正常。是否有更博学的人知道这是否与字形有关?
谢谢 !