Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertical align with Core Text?

An image clarifying things

How do I change the vertical alignment of the text in a CTFramesetter frame? I want my text to be in the middle instead of being at the top. I am using Core Text framework. There is a setting of the paragraph to change horizontal aligment but not vertical.

like image 379
Kristina Brooks Avatar asked Jul 19 '10 19:07

Kristina Brooks


People also ask

How do you vertically align text in CSS?

To center both vertically and horizontally, use padding and text-align: center : I am vertically and horizontally centered.

How do I vertically center text in a div?

Answer: Use the CSS line-height property Suppose you have a div element with the height of 50px and you have placed some link inside the div that you want to align vertically center. The simplest way to do it is — just apply the line-height property with value equal to the height of div which is 50px .

How do you vertically align text in a block element?

According to the CSS Flexible Box Layout Module, you can declare the a element as a flex container (see figure) and use align-items to vertically align text along the cross axis (which is perpendicular to the main axis). All you need to do is: display: flex; align-items: center; See this fiddle.


2 Answers

Finally figured it out ...

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));
like image 115
Kristina Brooks Avatar answered Oct 19 '22 09:10

Kristina Brooks


Thanks Nick, that was a great snippet.

Just expanding on that, if your doing Top, Middle and Bottom alignment with an enum, for example you could do it like so:

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));  
}
like image 26
Ken Avatar answered Oct 19 '22 08:10

Ken