问题描述
如何考虑字母的实际可见大小,而不是字体大小,将UILabel中的单个字母垂直居中.例如,我需要字母"f"和"o"准确位于标签的中间.
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.
我试图将标签渲染为图像,裁剪透明像素,然后设置UIImageView的中心,但是它总是比实际标签稍微模糊.
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.
如何实现?预先感谢.
推荐答案
我认为您需要深入研究核心文本才能获得执行此操作所需的字形指标.
I think you need to delve into core text to get the kind of glyph metrics needed to do this.
然后,您可以调整标签的位置,以使文本最终显示在所需的位置,而不是尝试在UILabel中移动文本.
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.
在下面的示例代码中,如果_myLabel包含一个当前具有基线的字符,则您希望文本居中,那么adjustLabel
将使可见字形在该行上居中.
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);
}
这篇关于在UILabel中垂直居中放置文本,具体取决于实际可见字母的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!