您可以使用字体的 capHeight。
Objective-C
NSTextAttachment *icon = [[NSTextAttachment alloc] init];
UIImage *iconImage = [UIImage imageNamed:@"icon.png"];
[icon setBounds:CGRectMake(0, roundf(titleFont.capHeight - iconImage.size.height)/2.f, iconImage.size.width, iconImage.size.height)];
[icon setImage:iconImage];
NSAttributedString *iconString = [NSAttributedString attributedStringWithAttachment:icon];
[titleText appendAttributedString:iconString];
迅速
let iconImage = UIImage(named: "icon.png")!
var icon = NSTextAttachment()
icon.bounds = CGRect(x: 0, y: (titleFont.capHeight - iconImage.size.height).rounded() / 2, width: iconImage.size.width, height: iconImage.size.height)
icon.image = iconImage
let iconString = NSAttributedString(attachment: icon)
titleText.append(iconString)
附件图像呈现在文本的基线上。并且它的y轴像核心图形坐标系一样反转。如果要向上移动图像,请将 设置bounds.origin.y
为正值。
图像应与文本的 capHeight 垂直居中对齐。所以我们需要设置bounds.origin.y
为(capHeight - imageHeight)/2
.
为了避免对图像产生一些锯齿状的影响,我们应该对 y 的小数部分进行四舍五入。但是字体和图像通常很小,即使是 1px 的差异也会使图像看起来像错位。所以我在划分之前应用了round函数。它使 y 值的小数部分变为 .0 或 .5
在您的情况下,图像高度大于字体的 capHeight。但是你可以用同样的方法。偏移 y 值将为负数。它将从基线的下方进行布局。
