3

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

CTFrame 裁剪第一行的示例

我认为我在设置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 帖子(这个这个)并不是很有帮助。

如何防止CTFrame剪切第一行?

- 编辑 -

减少lineheight到 20:

lineheight从第二行开始被尊重,但第一行文本的基线低于顶部 20 以内。

在此处输入图像描述

4

2 回答 2

0
于 2012-10-28T19:04:54.937 回答
0

I managed to fix the problem. In the end it turned out to be the location at which I flipped the coordinate system, and by flipping it earlier on in the code the problem fixed itself.

于 2012-11-08T16:15:20.630 回答