Macos 在NSTextView中调整图像大小以适合

Macos 在NSTextView中调整图像大小以适合,macos,nstextview,nsimage,nstextattachment,Macos,Nstextview,Nsimage,Nstextattachment,我有nsattributestring带有嵌入图像的对象。这些将在NSTextViews中显示。在iOS中,我能够调整NSTextAttachment的边界,这使图像更适合 extension NSTextAttachment { func setImageWidth(width: CGFloat, range: NSRange) { var thisImage = image if thisImage == nil { thisI

我有
nsattributestring
带有嵌入图像的对象。这些将在
NSTextView
s中显示。在iOS中,我能够调整
NSTextAttachment
的边界,这使图像更适合

extension NSTextAttachment {
    func setImageWidth(width: CGFloat, range: NSRange) {
        var thisImage = image
        if thisImage == nil {
            thisImage = imageForBounds(bounds, textContainer: nil, characterIndex: range.location)
        }
        if thisImage != nil {
            let ratio = thisImage!.size.height / thisImage!.size.width
            bounds = CGRectMake(bounds.origin.x, bounds.origin.y, width, ratio * width)
            print("New Bounds: \(bounds)")
        }
    }
}
这段代码也在OSX上运行,但实际上并没有调整图像的大小。下面您可以看到,图像周围有一个大小正确的框,但实际图像溢出了框

我还遵循了以下指南:。这会将代码移动到子类,但具有相同的效果

有什么建议吗?除了
NSTextAttachment.bounds
之外,还有什么我应该调整的吗

更新

我发现修改
NSImage
size
组件很有效!但是,它现在将我的所有图像都显示在上方,但大小正确(

解决了

extension NSImage {
    func resizeToFit(containerWidth: CGFloat) {
        var scaleFactor : CGFloat = 1.0
        let currentWidth = self.size.width
        let currentHeight = self.size.height
        if currentWidth > containerWidth {
            scaleFactor = (containerWidth * 0.9) / currentWidth
        }
        let newWidth = currentWidth * scaleFactor
        let newHeight = currentHeight * scaleFactor

        self.size = NSSize(width: newWidth, height: newHeight)
        print("Size: \(size)")
    }
}

正如我在更新中提到的,您需要更改
NSImage.size
。翻转来自我在问题中的链接中留下的一个子类。一旦我回到主类,它就可以工作了!

如果您希望允许用户调整图像大小,我已经创建了一个库来实现这一点:。