NSImageView的时候,如果图片比View的边框小,图片会被放大以适应边框的大小。但是如果图片宽高比和View的宽高比不一致时,图片是不会填满整个View的,这个时候就会有黑边出现(不一定是黑色,根据View的背景色而定)。在iOS里可以选择UIViewContentModeScaleAspectFill来填满整个View,但是在Cocoa中是没有这个选项的。
所以我们应该调整图像大小以适应新大小,保持纵横比不变。如果图像小于新尺寸,则按比例放大并填充新帧。如果图像大于新尺寸,则缩小尺寸,并填充新框架。
- (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;
}
NSImage *newImg = [self resizeImage:@"原图" size:@"想要的大小"];
[aNSImageView setImage:newImg];