考虑到字母的实际可见大小,而不是字体大小,如何在 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/