Guy*_*ood 5 iphone objective-c nsstring core-text ios
我有一个自定义的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);
}
Run Code Online (Sandbox Code Playgroud)
在另一个类中,我然后尝试使用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);
Run Code Online (Sandbox Code Playgroud)
getAttributedString方法在上面.问题是textView的高度略微过短,因此切断了文本的最后一行.任何人都可以提出什么问题?
另外,在旁注中,为什么boundingRectWithSize中的大小必须是315(即略短于屏幕宽度)而不是320才能工作?在320处,textView对于屏幕来说略微过宽.
编辑 - 这似乎只发生在某些字体上 - 例如Verdana工作正常.更有知识的人知道这是否与字形有关吗?
谢谢 !
| 归档时间: |
|
| 查看次数: |
5447 次 |
| 最近记录: |