Vertically center text in UILabel depending on actual visible letter height

三世轮回 提交于 2019-11-28 06:06:10

问题


How can I vertically center a single letter in a UILabel considering the actual visible size of the letter, not the font size. For example, I need letters 'f' and 'o' to be exactly in the middle of the label.

I have tried to render the label to an image, crop the transparent pixels and then set the center of the UIImageView BUT it always appears slightly more blurry than the actual label.

How can this be achieved? Thanks in advance.


回答1:


I think you need to delve into core text to get the kind of glyph metrics needed to do this.

Then, rather than trying to move the text inside the UILabel, you could adjust the label's position so that the text ends up where you want it.

In the following example code, if _myLabel contains a character that currently has its baseline where you want the text centered then adjustLabel will center the visible glyph on that line.

In more realistic code you might calculate the entire bounds for the label based on the glyph bounds.

#import <CoreText/CoreText.h>

(And add the framework to your project. Then...)

- (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);
}


来源:https://stackoverflow.com/questions/17328689/vertically-center-text-in-uilabel-depending-on-actual-visible-letter-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!