【问题标题】:Vertically center text in UILabel depending on actual visible letter height根据实际可见字母高度在 UILabel 中垂直居中文本
【发布时间】:2013-06-24 02:25:22
【问题描述】:

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

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

如何做到这一点?提前致谢。

【问题讨论】:

    标签: ios objective-c text uilabel vertical-alignment


    【解决方案1】:

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

    然后,与其尝试在 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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-12
      • 2015-08-25
      • 2014-05-26
      • 2013-10-08
      • 1970-01-01
      • 1970-01-01
      • 2012-06-11
      • 2015-03-31
      相关资源
      最近更新 更多