【问题标题】:Images being flipped when adding to NSAttributedString添加到 NSAttributedString 时翻转的图像
【发布时间】:2017-10-10 12:04:18
【问题描述】:

在调整 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)

图像垂直翻转的位置。

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

【问题讨论】:

    标签: swift macos cocoa nsattributedstring nsimage


    【解决方案1】:

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

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

    bounds参数定义如下:

    “定义文本坐标系中接收器图形表示的布局边界。”

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

    希望对您有所帮助。

    【讨论】:

    • 你找到办法了吗@jimwan?
    【解决方案2】:

    我想通了,它比我制作的要简单得多。

    因为图像是在一个 NSAttribuetdString 中被附加到一个 NSTextView 我不需要调整 NSAttributedString 中的每个图像的大小,而我只需要在 NSTextView 内设置附件缩放与

    markdown.layoutManager?.defaultAttachmentScaling = NSImageScaling.scaleProportionallyDown 
    

    只需要一行

    【讨论】:

    • markdown.layoutManager?.defaultAttachmentScaling 是什么,我遇到了同样的问题,你能告诉我如何解决吗?
    • @jimwan markdownNSTextView。所以对于你的NSTextView,只需设置属性layoutManager?.defaultAttachmentScaling = NSImageScaling.scaleProportionallyDown
    • 假设您只有一个 NSAttirbutedString 并且没有文本视图或布局管理器。你会怎么做?
    猜你喜欢
    • 2022-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    相关资源
    最近更新 更多