Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ios - Vertically center text in UILabel depending on actual visible letter height

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...