【问题标题】:Resize image in NSTextView to fit调整 NSTextView 中的图像大小以适应
【发布时间】:2016-08-13 21:51:33
【问题描述】:

我有带有嵌入图像的 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 上运行,但实际上并不会调整图像大小。下图可以看到,图片周围有一个大小正确的框,但实际图片超出了框。

我还遵循了以下指南:Implementing Rich Text with Images on OS X and iOS。这会将代码移动到子类中,但效果相同。

有什么建议吗?除了NSTextAttachment.bounds,我还有什么需要调整的吗?

更新

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

【问题讨论】:

标签: macos nstextview nsimage nstextattachment


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

【讨论】:

    猜你喜欢
    • 2014-05-05
    • 2012-09-15
    • 2011-02-03
    • 2020-06-03
    • 2011-04-17
    • 1970-01-01
    • 2015-07-16
    • 2012-05-02
    相关资源
    最近更新 更多