我正在尝试显示一个简单的NSImageView,它的图像居中而不像这样缩放它:

就像iOS设置UIView的contentMode = UIViewContentModeCenter一样
所以我尝试了所有NSImageScaling值,这是我选择NSScaleNone时得到的

我真的不明白发生了什么: - /
您可以手动生成正确大小和内容的图像,并将其设置为NSImageView的图像,以便NSImageView不需要执行任何操作.
NSImage *newImg = [self resizeImage:sourceImage size:newSize];
[aNSImageView setImage:newImg];
Run Code Online (Sandbox Code Playgroud)
以下功能调整图像大小以适应新大小,保持纵横比不变.如果图像小于新尺寸,则按比例放大并填充新帧.如果图像大于新尺寸,则缩小尺寸,并填充新框架
- (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;}
Run Code Online (Sandbox Code Playgroud)