垂直对齐核心文本?

Kri*_*oks 8 alignment core-text

澄清事物的图像

如何更改CTFramesetter框架中文本的垂直对齐方式?我希望我的文字在中间,而不是在顶部.我正在使用Core Text框架.该段落的设置可以更改水平对齐但不是垂直对齐.

Kri*_*oks 7

终于想通了......

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));
Run Code Online (Sandbox Code Playgroud)


小智 5

谢谢尼克,这是一个很棒的片段。

只是扩展一下,如果您使用枚举进行顶部,中间和底部对齐,例如,您可以这样做:

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));  
}
Run Code Online (Sandbox Code Playgroud)