139

我想将NSTextAttachment图像附加到我的属性字符串并使其垂直居中。

我使用以下代码来创建我的字符串:

NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:DDLocalizedString(@"title.upcomingHotspots") attributes:attrs];
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [[UIImage imageNamed:@"help.png"] imageScaledToFitSize:CGSizeMake(14.f, 14.f)];
cell.textLabel.attributedText = [str copy];

但是,图像似乎与单元格的顶部对齐textLabel

文字附件偏移问题截图

如何更改绘制附件的矩形?

4

10 回答 10

249

您可以使用字体的 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 值将为负数。它将从基线的下方进行布局。

在此处输入图像描述

于 2017-07-18T08:12:42.967 回答
115

试试- [NSTextAttachment bounds]。不需要子类化。

对于上下文,我正在渲染一个UILabel用作附件图像,然后像这样设置边界: attachment.bounds = CGRectMake(0, self.font.descender, attachment.image.size.width, attachment.image.size.height)标签图像中的文本基线和属性字符串中的文本根据需要排列。

于 2015-02-05T22:22:36.237 回答
65

NSTextAttachment您可以通过子类化和覆盖来更改 rect attachmentBoundsForTextContainer:proposedLineFragment:glyphPosition:characterIndex:。例子:

- (CGRect)attachmentBoundsForTextContainer:(NSTextContainer *)textContainer proposedLineFragment:(CGRect)lineFrag glyphPosition:(CGPoint)position characterIndex:(NSUInteger)charIndex {
    CGRect bounds;
    bounds.origin = CGPointMake(0, -5);
    bounds.size = self.image.size;
    return bounds;
}

这不是一个完美的解决方案。您必须“通过眼睛”找出 Y 原点,如果您更改字体或图标大小,您可能需要更改 Y 原点。但是我找不到更好的方法,除了将图标放在单独的图像视图中(这有其自身的缺点)。

于 2014-09-29T19:32:43.873 回答
64

我找到了一个完美的解决方案,虽然对我来说就像一个魅力,但是你必须自己尝试一下(可能常数取决于设备的分辨率,也许还有什么;)

func textAttachment(fontSize: CGFloat) -> NSTextAttachment {
    let font = UIFont.systemFontOfSize(fontSize) //set accordingly to your font, you might pass it in the function
    let textAttachment = NSTextAttachment()
    let image = //some image
    textAttachment.image = image
    let mid = font.descender + font.capHeight
    textAttachment.bounds = CGRectIntegral(CGRect(x: 0, y: font.descender - image.size.height / 2 + mid + 2, width: image.size.width, height: image.size.height))
    return textAttachment
}

应该可以工作并且不应该以任何方式模糊(感谢CGRectIntegral

于 2015-12-01T18:17:04.757 回答
42

What about:

CGFloat offsetY = -10.0;

NSTextAttachment *attachment = [NSTextAttachment new];
attachment.image = image;
attachment.bounds = CGRectMake(0.0, 
                               offsetY, 
                               attachment.image.size.width, 
                               attachment.image.size.height);

No subclassing needed

于 2015-04-29T21:11:08.103 回答
15

@Travis 是正确的,偏移量是字体下降器。如果还需要缩放图像,则需要使用 NSTextAttachment 的子类。以下是受本文启发的代码。我也将它作为要点发布。

import UIKit

class ImageAttachment: NSTextAttachment {
    var verticalOffset: CGFloat = 0.0

    // To vertically center the image, pass in the font descender as the vertical offset.
    // We cannot get this info from the text container since it is sometimes nil when `attachmentBoundsForTextContainer`
    // is called.

    convenience init(_ image: UIImage, verticalOffset: CGFloat = 0.0) {
        self.init()
        self.image = image
        self.verticalOffset = verticalOffset
    }

    override func attachmentBoundsForTextContainer(textContainer: NSTextContainer, proposedLineFragment lineFrag: CGRect, glyphPosition position: CGPoint, characterIndex charIndex: Int) -> CGRect {
        let height = lineFrag.size.height
        var scale: CGFloat = 1.0;
        let imageSize = image!.size

        if (height < imageSize.height) {
            scale = height / imageSize.height
        }

        return CGRect(x: 0, y: verticalOffset, width: imageSize.width * scale, height: imageSize.height * scale)
    }
}

使用如下:

var text = NSMutableAttributedString(string: "My Text")
let image = UIImage(named: "my-image")!
let imageAttachment = ImageAttachment(image, verticalOffset: myLabel.font.descender)
text.appendAttributedString(NSAttributedString(attachment: imageAttachment))
myLabel.attributedText = text
于 2015-03-22T22:33:35.090 回答
10

如果你有一个非常大的上升点并且想像我一样将图像居中(大写高度的中心)试试这个

let attachment: NSTextAttachment = NSTextAttachment()
attachment.image = image
if let image = attachment.image{
    let y = -(font.ascender-font.capHeight/2-image.size.height/2)
    attachment.bounds = CGRect(x: 0, y: y, width: image.size.width, height: image.size.height).integral
}

y计算如下图

在此处输入图像描述

请注意,y 值为 0,因为我们希望图像从原点向下移动

如果您希望它位于整个标签的中间。使用此 y 值:

let y = -((font.ascender-font.descender)/2-image.size.height/2)
于 2017-04-03T19:10:12.787 回答
9

我们可以在 swift 4 中做一个扩展,生成一个带有中心图像的附件,如下所示:

extension NSTextAttachment {
    static func getCenteredImageAttachment(with imageName: String, and 
    font: UIFont?) -> NSTextAttachment? {
        let imageAttachment = NSTextAttachment()
    guard let image = UIImage(named: imageName),
        let font = font else { return nil }

    imageAttachment.bounds = CGRect(x: 0, y: (font.capHeight - image.size.height).rounded() / 2, width: image.size.width, height: image.size.height)
    imageAttachment.image = image
    return imageAttachment
    }
}

然后您可以拨打电话发送图像的名称和字体:

let imageAttachment = NSTextAttachment.getCenteredImageAttachment(with: imageName,
                                                                   and: youLabel?.font)

然后将 imageAttachment 附加到属性字符串

于 2018-01-17T12:28:16.557 回答
2

就我而言,调用 sizeToFit() 有帮助。在 Swift 5.1 中

在您的自定义标签内:

func updateUI(text: String?) {
    guard let text = text else {
        attributedText = nil
        return
    }

    let attributedString = NSMutableAttributedString(string:"")

    let textAttachment = NSTextAttachment ()
    textAttachment.image = image

    let sizeSide: CGFloat = 8
    let iconsSize = CGRect(x: CGFloat(0),
                           y: (font.capHeight - sizeSide) / 2,
                           width: sizeSide,
                           height: sizeSide)
    textAttachment.bounds = iconsSize

    attributedString.append(NSAttributedString(attachment: textAttachment))
    attributedString.append(NSMutableAttributedString(string: text))
    attributedText = attributedString

    sizeToFit()
}
于 2020-02-11T14:57:46.737 回答
0

Please use -lineFrag.size.height/5.0 for the bounds height. This exactly centres the image and aligned with text for all the size of fonts

override func attachmentBoundsForTextContainer(textContainer: NSTextContainer, proposedLineFragment lineFrag: CGRect, glyphPosition position: CGPoint, characterIndex charIndex: Int) -> CGRect
{
    var bounds:CGRect = CGRectZero

    bounds.size = self.image?.size as CGSize!
    bounds.origin = CGPointMake(0, -lineFrag.size.height/5.0);

    return bounds;
}
于 2015-03-16T05:40:59.267 回答