Confused about scaling NSImageView

I am trying to show a simple NSImageView , with the image centered without scaling as follows:

Just like iOS does when you set an UIView's contentMode = ** UIViewContentModeCenter **

Like iOS, when you set UIView contentMode = UIViewContentModeCenter

So, I tried all the NSImageScaling values, this is what I get when I select NSScaleNone

I really don't understand what's going on: - /

I really don't understand what is going on: - /

+7
source share
4 answers

You can manually create an image of the correct size and content and set its NSImageView image so that NSImageView does nothing.

NSImage *newImg = [self resizeImage:sourceImage size:newSize]; [aNSImageView setImage:newImg]; 

The following function resizes the image to the new size, keeping the aspect ratio. If the image is smaller than the new size, it is scaled and filled with a new frame. If the image is larger than the new size, it is reduced and filled with a new frame

 - (NSImage*) resizeImage:(NSImage*)sourceImage size:(NSSize)size{ NSRect targetFrame = NSMakeRect(0, 0, size.width, size.height); NSImage* targetImage = [[NSImage alloc] initWithSize:size]; NSSize sourceSize = [sourceImage size]; float ratioH = size.height/ sourceSize.height; float ratioW = size.width / sourceSize.width; NSRect cropRect = NSZeroRect; if (ratioH >= ratioW) { cropRect.size.width = floor (size.width / ratioH); cropRect.size.height = sourceSize.height; } else { cropRect.size.width = sourceSize.width; cropRect.size.height = floor(size.height / ratioW); } cropRect.origin.x = floor( (sourceSize.width - cropRect.size.width)/2 ); cropRect.origin.y = floor( (sourceSize.height - cropRect.size.height)/2 ); [targetImage lockFocus]; [sourceImage drawInRect:targetFrame fromRect:cropRect //portion of source image to draw operation:NSCompositeCopy //compositing operation fraction:1.0 //alpha (transparency) value respectFlipped:YES //coordinate system hints:@{NSImageHintInterpolation: [NSNumber numberWithInt:NSImageInterpolationLow]}]; [targetImage unlockFocus]; return targetImage;} 
+5
source

Here's the awesome class for NSImage: NSImage + ContentMode

It allows content modes such as on iOS, works great.

+1
source

Set the image scaling property to NSImageScaleAxesIndependently, which will scale the image to fill the rectangle. This will not keep the proportion.

+1
source

To get the desired results, where the image will expand to fit the view, you should use NSScaleToFit. This will change the aspect ratio of the photo.

If you need the equivalent of UIViewContentModeScaleAspectFill, where the proportions of the image are kept the same, the image is enlarged to fill the gap and its overflowing areas are cropped, then check this guy. NSImage Category:

http://rheard.com/blog/making-nsimages-resizable/

This is probably what you want.

0
source

All Articles