简体   繁体   中英

Resize image in NSTextView to fit

I have NSAttributedString objects with embedded images. These are being presented in NSTextView s. In iOS, I was able to resize the bounds of NSTextAttachment , and this makes the image fit.

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

This code also runs on OSX, but it does not actually resize the image. Below you can see, there is a box of the correct size around the image, but the actual image overflows the box.

在此处输入图片说明

I have also followed the following guide: Implementing Rich Text with Images on OS X and iOS . This moves the code to subclasses, but has the same effect.

Any suggestions? Is there something besides NSTextAttachment.bounds that I should be adjusting?

UPDATE

I found that modifying the size component of NSImage works! However, it is now showing all my images upside, but at the correct size. :(

Solved!

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

As I mentioned in the update, you need to change the NSImage.size . The flip was coming from one of the subclasses I had left in there from the link in the question. Once I went back to the main classes, it works!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM