1
votes

Im wondering is that possible or no, and if yes, how can I reach that. I have NSImageView of size 120x120. I want to put an NSImage inside that,but scaled a bit different then regular way. So, lets say I have an image of 500x800 that I want to put inside square view. What I want to reach is - take the square area of size 500x500, right from the center of initial image image and then scale down that square to fit 120x120 size of nsimageview.

Is there any way to do that?

Also would be good not to create separate image file for that thumbnail.

1

1 Answers

2
votes

Ok, so I have found how to do that myself.

1) You need to cut a rectangle of destination size from existing image 2) Create a NSImage from that rectangle and image data.

        var originalImage : NSImage = NSImage()

        if(FileManager.default.fileExists(atPath: self.fileUrl.absoluteURL.path))
        {
            originalImage = NSImage(byReferencing: self.fileUrl.absoluteURL)
        }
        else
        {
            originalImage = NSImage(named: "NoImage")!
        }

        let originalSize = originalImage.size
        var sideSize : CGFloat = 0
        //2. get size of square, by checking what side is smaller
        if(originalSize.width > originalSize.height)
        {
            sideSize = originalSize.height
        }
        else
        {
            sideSize = originalSize.width
        }

        var originalImageRect : CGRect = CGRect(x: 0, y: 0, width: originalSize.width, height: originalSize.height)
        guard let imageRef = originalImage.cgImage(forProposedRect: &originalImageRect, context: nil, hints: nil) else { return }

        let thumbnailRect = CGRect(x: (originalSize.width / 2 - sideSize / 2), y: (originalSize.height / 2 - sideSize / 2), width: sideSize, height: sideSize)

        let drawImage = imageRef.cropping(to: thumbnailRect);

        let newImage = NSImage(cgImage: drawImage!, size: NSSize(width: SLIDE_WIDTH, height: SLIDE_HEIGHT))

        OperationQueue.main.addOperation{
            self.thumbnail = newImage
        }