I had difficulty trying to figure out how to make Aspect Fill Clip to Bounds :
Image courtesy: https://osxentwicklerforum.de/index.php/Thread/28812-NSImageView-Scaling-Seitenverh%C3%A4ltnis/
Finally, I created my own subclass of NSImageView, hope this can help someone:
import Cocoa @IBDesignable class NSImageView_ScaleAspectFill: NSImageView { @IBInspectable var scaleAspectFill : Bool = false override func awakeFromNib() { // Scaling : .scaleNone mandatory if scaleAspectFill { self.imageScaling = .scaleNone } } override func draw(_ dirtyRect: NSRect) { if scaleAspectFill, let _ = self.image { // Compute new Size let imageViewRatio = self.image!.size.height / self.image!.size.width let nestedImageRatio = self.bounds.size.height / self.bounds.size.width var newWidth = self.image!.size.width var newHeight = self.image!.size.height if imageViewRatio > nestedImageRatio { newWidth = self.bounds.size.width newHeight = self.bounds.size.width * imageViewRatio } else { newWidth = self.bounds.size.height / imageViewRatio newHeight = self.bounds.size.height } self.image!.size.width = newWidth self.image!.size.height = newHeight } // Draw AFTER resizing super.draw(dirtyRect) } }
Plus it's @IBDesignable so you can install it on StoryBoard
WARNINGS
I am new to MacOS Swift development, I came from iOS development, so I was surprised that I could not find the clipToBound property, maybe it exists, and I could not find it!
As for the code, I suspect that it consumes a lot and also has a side effect for changing the original image ratio over time. This side effect seemed insignificant to me.
Once again, if this is a setting that allows NSImageView crop borders, remove this answer:]
Olympiloutre
source share