Вертикальное выравнивание с основным текстом?

Изображение, проясняющее ситуацию

Как изменить вертикальное выравнивание текста во фрейме CTFramesetter? Я хочу, чтобы мой текст был посередине, а не вверху. Я использую фреймворк Core Text. Есть настройка абзаца на изменение выравнивания по горизонтали, но не по вертикали.


person Kristina Brooks    schedule 19.07.2010    source источник


Ответы (4)


Наконец-то разобрался...

CGRect boundingBox = CTFontGetBoundingBox(font);

//Get the position on the y axis
float midHeight = self.frame.size.height / 2;
midHeight -= boundingBox.size.height / 2;

CGPathAddRect(path, NULL, CGRectMake(0, midHeight, self.frame.size.width, boundingBox.size.height));
person Kristina Brooks    schedule 27.07.2010
comment
Это не работает для некоторых шрифтов. Только что проверил с использованием шрифта AcademyEngravedLetPlain, и шрифт не рисуется - person Coolant; 05.12.2012
comment
Но мне удалось это решить, установив высоту прямоугольного размера в качестве исходной высоты границ, а не высоты ограничивающей коробки. - person Coolant; 05.12.2012
comment
Вы можете использовать размер, возвращаемый CTFramesetterSuggestFrameSizeWithConstraints, для вычисления midHeight, он поддерживает несколько строк. - person ıɾuǝʞ; 03.04.2013

Спасибо, Ник, это был отличный фрагмент.

Просто расширяя это, если вы выполняете выравнивание Top, Middle и Bottom с перечислением, например, вы можете сделать это так:

if (VerticalAlignmentTop == currentTextAlignment) {
    CGPathAddRect(path, NULL, rect); // Draw normally (top)
}
else if (VerticalAlignmentMiddle == currentTextAlignment) {
    CGRect boundingBox = CTFontGetBoundingBox(fontRef);

    //Get the position on the y axis (middle)
    float midHeight = rect.size.height / 2;
    midHeight -= boundingBox.size.height / 2;

    CGPathAddRect(path, NULL, CGRectMake(0, midHeight, rect.size.width, boundingBox.size.height));  
}
else {
    CGRect boundingBox = CTFontGetBoundingBox(fontRef);

    CGPathAddRect(path, NULL, CGRectMake(0, 0, rect.size.width, boundingBox.size.height));  
}
person Ken    schedule 17.11.2011

Вы можете использовать [NSStringboundingRectWithSize:options:attributes:context:], чтобы получить прямоугольник ограничивающей рамки вашей строки, что также позволяет использовать многострочный текст. В методе рисования текста сделайте следующее (RECT — это прямоугольник, в котором вы хотите нарисовать текст):

// get the graphics context
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);

// flip the context coordinate
CGContextTranslateCTM(context, 0.0f, 2*RECT.origin.y+RECT.size.height);
CGContextScaleCTM(context, 1.0f, -1.0f);

// Set the text matrix.
CGContextSetTextMatrix(context, CGAffineTransformIdentity);

// set text horizontal alignment
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.alignment = NSTextAlignmentCenter;

NSDictionary *attributes = @{NSParagraphStyleAttributeName:paragraphStyle, NSFontAttributeName:YOUR_FONT, NSForegroundColorAttributeName:TEXT_COLOR};
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:YOUR_TEXT attributes:attributes];

CGMutablePathRef path = CGPathCreateMutable();

// set text vertical alignment
CGSize textSize = [text boundingRectWithSize:RECT.size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
CGPathAddRect(path, NULL, CGRectMake(RECT.origin.x, RECT.origin.y-(RECT.size.height-textSize.height)/2.0f, RECT.size.width, RECT.size.height));

CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attrString);
CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, attrString.length), path, NULL);
CTFrameDraw(frame, context);

CFRelease(frame);
CFRelease(path);
CFRelease(frameSetter);

[attrString release];
[paragraphStyle release];

CGContextRestoreGState(context);
person Elias Ma    schedule 10.12.2013

Это объясняет тот факт, что во фрейме можно использовать несколько типов и стилей шрифта (рассчитывается как высота, так и ширина текста, посмотрите в блоке if(index == lastLineIndex), где вычисляется высота):

- (CGSize) measureFrame: (CTFrameRef) frame forContext: (CGContext *) cgContext
{
    CGPathRef framePath = CTFrameGetPath(frame);
    CGRect frameRect = CGPathGetBoundingBox(framePath);

    CFArrayRef lines = CTFrameGetLines(frame);
    CFIndex numLines = CFArrayGetCount(lines);

    CGFloat maxWidth = 0;
    CGFloat textHeight = 0;

    // Now run through each line determining the maximum width of all the lines.
    // We special case the last line of text. While we've got it's descent handy,
    // we'll use it to calculate the typographic height of the text as well.

    CFIndex lastLineIndex = numLines - 1;
    for(CFIndex index = 0; index < numLines; index++)
    {
        CGFloat ascent, descent, leading, width;
        CTLineRef line = (CTLineRef) CFArrayGetValueAtIndex(lines, index);
        width = CTLineGetTypographicBounds(line, &ascent,  &descent, &leading);

        if(width > maxWidth)
        {
            maxWidth = width;
        }

        if(index == lastLineIndex)
        {
            // Get the origin of the last line. We add the descent to this
            // (below) to get the bottom edge of the last line of text.

            CGPoint lastLineOrigin;
            CTFrameGetLineOrigins(frame, CFRangeMake(lastLineIndex, 1), &lastLineOrigin);

            // The height needed to draw the text is from the bottom of the last line
            // to the top of the frame.

            textHeight =  CGRectGetMaxY(frameRect) - lastLineOrigin.y + descent;
        }
    }

    // For some text the exact typographic bounds is a fraction of a point too
    // small to fit the text when it is put into a context. We go ahead and round
    // the returned drawing area up to the nearest point.  This takes care of the
    // discrepencies.

    return CGSizeMake(ceil(maxWidth), ceil(textHeight));
}

Ссылка: Скотт Томпсон (http://lists.apple.com/archives/quartz-dev/2008/Mar/msg00079.html)

person Ser Pounce    schedule 14.03.2012