gpt4 book ai didi

objective-c - CTFrame 裁剪第一行文本

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:44:08 24 4
gpt4 key购买 nike

我在使用 Core Text 时遇到问题,我在 CTFrame 中显示的文本的第一行在顶部被截断,如下面的屏幕截图所示,字符“B”:

Example of CTFrame clipping first line

我认为我在 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 onethis one)并不是很有帮助。

如何防止 CTFrame 剪切第一行?

--编辑--

lineheight 减少到 20:

从第二行开始的

lineheight 是受尊重的,但第一行文本的基线距离顶部不到 20。

enter image description here

最佳答案

此处 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com