Cocoa 怎样使NSImageView的图片正确的满屏放大缩小而没有黑边

在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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值