作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我在使用 Core Text 时遇到问题,我在 CTFrame
中显示的文本的第一行在顶部被截断,如下面的屏幕截图所示,字符“B”:
我认为我在 CTFrame
中设置行距时做错了什么。我的代码如下:
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
NSAttributedString *myString;
//Create the rectangle into which we'll draw the text
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, self.bounds);
//Flip the coordinate system
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
//Setup leading (line height)
CGFloat lineHeight = 25;
CTParagraphStyleSetting settings[] = {
{ kCTParagraphStyleSpecifierMinimumLineHeight, sizeof(CGFloat), &lineHeight },
{ kCTParagraphStyleSpecifierMaximumLineHeight, sizeof(CGFloat), &lineHeight },
};
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(settings, sizeof(settings) / sizeof(settings[0]));
NSDictionary * attrs = [[NSDictionary alloc] initWithObjectsAndKeys:
(__bridge id)CTFontCreateWithName((__bridge CFStringRef) font.fontName, font.pointSize, NULL) ,
(NSString*)kCTFontAttributeName,
(id)textColor.CGColor,
(NSString*)kCTForegroundColorAttributeName,
(__bridge id) paragraphStyle,
kCTParagraphStyleAttributeName,
nil];
myString = [[NSAttributedString alloc] initWithString:text attributes:attrs];
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)myString);
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0,[myString length]), path, NULL);
CTFrameDraw(frame, context);
CFRelease(frame);
CFRelease(framesetter);
CFRelease(path);
}
其他 SO 帖子(this one 和 this one)并不是很有帮助。
如何防止 CTFrame
剪切第一行?
--编辑--
将 lineheight
减少到 20:
lineheight
是受尊重的,但第一行文本的基线距离顶部不到 20。
最佳答案
此处 CGFloat lineHeight = 25;
我确信(从您的屏幕截图中)它小于您当前使用的字体大小 (font.pointSize
)。这是裁剪文本顶部的唯一原因,因为文本大小无法适应 25 点的高度。
你有两个选择:
1) 删除paragraphStyle
及其相关代码。用以下代码替换你的 NSDictionary * attrs = …
。
NSDictionary * attrs = [[NSDictionary alloc] initWithObjectsAndKeys:
(__bridge id)CTFontCreateWithName((__bridge CFStringRef) font.fontName, font.pointSize, NULL) ,
(NSString*)kCTFontAttributeName,
(id)textColor.CGColor, (NSString*)kCTForegroundColorAttributeName,
nil];
CTFrameDraw()
会自动处理行高。
2) 或者始终提供大于最大字体大小的 lineHeight。比如 lineHeight = font.pointSize + somemargine
;
要理解上面的解释,试试这个:在您当前的代码中设置您的 lineHeight = 20;
;您可以看到更多文本将从顶行剪裁,第二行文本将更加靠近其顶行底部。
关于objective-c - CTFrame 裁剪第一行文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13086071/
我是一名优秀的程序员,十分优秀!