代码之家  ›  专栏  ›  技术社区  ›  Luka Kerr Max Dercum

添加到NSAttribute String时翻转的图像

  •  1
  • Luka Kerr Max Dercum  · 技术社区  · 7 年前

    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)
    

    图像垂直翻转的位置。

    2 回复  |  直到 7 年前
        1
  •  0
  •   Marcus    7 年前

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

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

    我知道当使用CoreText来布局文本时,需要翻转坐标,所以我应该想象一下,您也需要用垂直反射来转换边界参数。

    希望这有帮助。

        2
  •  0
  •   Luka Kerr Max Dercum    7 年前

    因为图像位于NSAttribute字符串中,并被附加到NSTextView中,所以我不需要调整NSAttribute字符串中的每个图像的大小,而只需在NSTextView中设置附件比例

    markdown.layoutManager?.defaultAttachmentScaling = NSImageScaling.scaleProportionallyDown 
    

    一行就够了