2

我有NSAttributedString嵌入图像的对象。这些在NSTextViews 中呈现。在 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 上运行,但它实际上并没有调整图像的大小。下面你可以看到,图像周围有一个大小正确的框,但实际图像溢出了框。

在此处输入图像描述

我还遵循了以下指南:在 OS X 和 iOS 上实现带有图像的富文本。这会将代码移动到子类,但效果相同。

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

更新

我发现修改size组件NSImage有效!但是,它现在显示我所有的图像,但尺寸正确。:(

4

1 回答 1

1

解决了!

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. 翻转来自我从问题中的链接留在其中的一个子类。一旦我回到主要课程,它就起作用了!

于 2016-08-14T01:03:29.357 回答