在Cocoa中使用NSImageView的时候,如果图片比View的边框小,图片会被放大以适应边框的大小。但是如果图片宽高比和View的宽高比不一致时,图片是不会填满整个View的,这个时候就会有黑边出现(不一定是黑色,根据View的背景色而定)。在iOS里可以选择UIViewContentModeScaleAspectFill来填满整个View,但是在Cocoa中是没有这个选项的。所以我们必须用另外一个方法。我们可以通过下面这个函数来产生一个新的NSImage, 这个image的大小可以设定为NSImageView的边框大小,这样这个函数就会自动生成一个合适的没有黑边的图片。然后设置这个新的NSImage为NSImageView的图像就可以了。
详细实例可以参考我在stackoverflow.com上的回答 : )
http://stackoverflow.com/questions/13750234/confused-about-nsimageview-scaling/18063883#18063883
NSImage *newImg = [self resizeImage:sourceImage size:newSize];
[aNSImageView setImage:newImg];
/**
Resize the image to fit the new size, keeping the aspect ration constant
If the image is smaller than the new size, it is scaled up and filled the new frame
If the image is larger than the new size, it is downsized, and filled the new frame
- SHAGRU.COM -
*/
- (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;
}