Mini Official
Mini Official

Reputation: 133

.aspectFill on NSImageView

I'm porting my SpriteKit app from iOS to MacOS. I am designing my main menu in the main.storyboard, and I have an image as the background. When I resize the window, however, my image does not fill the whole screen.

I've tried:

.scaleAxesIndependently //???
.scaleNone //Centre
.scaleProportionallyDown //???
.scaleProportionallyUpOrDown //AspectFit

but none are the same as .aspectFill.

I am using swift

Upvotes: 4

Views: 1256

Answers (1)

AamirR
AamirR

Reputation: 12198

Subclassing NSImageView and overriding intrinsicContentSize you will be able to resizing image keeping aspect ratio, like so:

class AspectFillImageView: NSImageView {
    override var intrinsicContentSize: CGSize {
        guard let img = self.image else { return .zero }

        let viewWidth = self.frame.size.width
        let ratio = viewWidth / img.size.width
        return CGSize(width: viewWidth, height: img.size.height * ratio)
    }
}

If you just want to fill the whole view ignoring the ratio, use this extension instead:

extension NSImage {
    func resize(to size: NSSize) -> NSImage {
        return NSImage(size: size, flipped: false, drawingHandler: {
            self.draw(in: $0)
            return true
        })
    }
}

Extension usage:

NSImage.resize(to: self.view.frame.size)

Upvotes: 2

Related Questions