美文网首页
Cocoa 怎样使NSImageView的图片正确的满屏放大缩小

Cocoa 怎样使NSImageView的图片正确的满屏放大缩小

作者: 皮蛋豆腐酱油 | 来源:发表于2019-12-16 14:02 被阅读0次
    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;
    }
    
    

    参考自:https://blog.csdn.net/shagru/article/details/9779183

    相关文章

      网友评论

          本文标题:Cocoa 怎样使NSImageView的图片正确的满屏放大缩小

          本文链接:https://www.haomeiwen.com/subject/vjxdnctx.html