添加到 NSAttributedString 时翻转图像

Images being flipped when adding to NSAttributedString

我在调整 NSAttributedString 中的图像大小时遇到​​一个奇怪的问题。调整大小扩展工作正常,但是当图像添加到 NSAttributedString 时,由于某种原因它会垂直翻转。

这是调整大小的扩展:

extension NSImage {
  func resize(containerWidth: CGFloat) -> NSImage {

    var scale : CGFloat = 1.0
    let currentWidth = self.size.width
    let currentHeight = self.size.height

    if currentWidth > containerWidth {
      scale = (containerWidth * 0.9) / currentWidth
    }

    let newWidth = currentWidth * scale
    let newHeight = currentHeight * scale

    self.size = NSSize(width: newWidth, height: newHeight)

    return self
  }
}

这里是对属性字符串中图像的枚举:

newAttributedString.enumerateAttribute(NSAttributedStringKey.attachment, in: NSMakeRange(0, newAttributedString.length), options: []) { value, range, stop in
    if let attachement = value as? NSTextAttachment {
        let image = attachement.image(forBounds: attachement.bounds, textContainer: NSTextContainer(), characterIndex: range.location)!

        let newImage = image.resize(containerWidth: markdown.bounds.width)
        let newAttribute = NSTextAttachment()
        newAttribute.image = newImage
        newAttributedString.addAttribute(NSAttributedStringKey.attachment, value: newAttribute, range: range)
    }
}

我设置了断点并检查了图像,它们都在正确的旋转中,除了到达这条线时:

newAttributedString.addAttribute(NSAttributedStringKey.attachment, value: newAttribute, range: range)

图像垂直翻转的位置。

我不知道是什么导致了这种垂直翻转。有办法解决这个问题吗?

如果您查看 NSTextAttachment 的开发者文档:

https://developer.apple.com/documentation/uikit/nstextattachment

bounds参数定义如下:

“定义接收者图形表示在文本坐标系中的布局范围。”

我知道在使用 CoreText 布局文本时,您需要翻转坐标,所以我想您也需要将 bounds 参数转换为垂直反射。

希望对您有所帮助。

我想出来了,它比我做的要简单得多。

因为图像在 NSAttribuetdString 中并被附加到 NSTextView 中,所以我不需要调整 NSAttributedString 中每个图像的大小,而我只需要使用

在 NSTextView 中设置附件缩放
markdown.layoutManager?.defaultAttachmentScaling = NSImageScaling.scaleProportionallyDown 

一行就够了