ios - 根据实际可见字母高度在 UILabel 中垂直居中文本

标签 ios objective-c text uilabel vertical-alignment

考虑到字母的实际可见大小,而不是字体大小,如何在 UILabel 中垂直居中单个字母。例如,我需要字母“f”和“o”正好位于标签的中间。

我尝试将标签渲染到图像,裁剪透明像素,然后设置 UIImageView 的中心,但它总是比实际标签显得稍微模糊。

如何实现这一目标?提前致谢。

最佳答案

我认为您需要深入研究核心文本以获得执行此操作所需的字形指标。

然后,您可以调整标签的位置,使文本最终位于您想要的位置,而不是尝试在 UILabel 内移动文本。

在以下示例代码中,如果 _myLabel 包含的字符当前的基线位于您希望文本居中的位置,则 adjustLabel 会将可见字形置于该行的中心。

在更实际的代码中,您可以根据字形边界计算标签的整个边界。

#import <CoreText/CoreText.h>

(并将框架添加到您的项目中。然后...)

- (void)adjustLabel
{
    UIFont *uiFont = _myLabel.font;

    CTFontRef ctFont = CTFontCreateWithName((__bridge CFStringRef)(uiFont.fontName), uiFont.pointSize, NULL);

    UniChar ch = [_myLabel.text characterAtIndex:0];
    CGGlyph glyph;

    if (CTFontGetGlyphsForCharacters (ctFont, &ch, &glyph, 1)) {

        CGRect bounds = CTFontGetBoundingRectsForGlyphs (ctFont, kCTFontOrientationDefault, &glyph, nil, 1);
        CGFloat offset = bounds.origin.y + bounds.size.height/2.0;
        CGRect labelBounds = _myLabel.bounds;
        labelBounds.origin.y += offset;
        _myLabel.bounds = labelBounds;
    }
    CFRelease(ctFont);
}

关于ios - 根据实际可见字母高度在 UILabel 中垂直居中文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17328689/

相关文章:

html - 如何将文本环绕在 div 按钮周围?

ios - build设置 : What changes should I do in the build settings so that on releasing the app it will show the languages on App Store as only English?

ios - 用图像突出显示 UITableViewCell

ios - XLPagerTabStrip 按钮栏宽度比导航栏宽

ios - iOS 中 NSURLConnection 的间歇性 SSL 错误

Python Pandas 从正则表达式中排除文本

ios - 在后台模式下循环

ios - 实例被释放,而键值观察者仍然在其中注册

iOS : NSString Evaluate String Expression

python - 在第一个逗号出现的地方拆分超过 10 个单词的行/句子