添加到NSAttributedString时图像被翻转 [英] Images being flipped when adding to NSAttributedString

查看:207
本文介绍了添加到NSAttributedString时图像被翻转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a strange problem when resizing an image that's in a NSAttributedString. The resizing extension is working fine, but when the image is added to the NSAttributedString, it gets flipped vertically for some reason.

这是调整大小的扩展名:

This is the resizing extension:

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
  }
}

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

And here is the enumeration over the images in the attributed string:

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)
    }
}

我已经设置了断点并检查了图像,它们都处于正确的旋转状态,除非到达此行:

I've set breakpoints and inspected the images, and they are all in the correct rotation, except when it reaches this line:

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

图像垂直翻转的地方.

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

I have no clue what could be causing this vertical flip. Is there a way to fix this?

推荐答案

我知道了,它比我做的要简单得多.

I figured it out and it was so much simpler than I was making it.

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

Because the image was in a NSAttribuetdString being appended into a NSTextView I didn't need to resize each image in the NSAttributedString, rather I just had to set the attachment scaling inside the NSTextView with

markdown.layoutManager?.defaultAttachmentScaling = NSImageScaling.scaleProportionallyDown 

只需要一行即可

这篇关于添加到NSAttributedString时图像被翻转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆