2012-12-06 71 views
7

我試圖用它來顯示一個簡單的NSImageView的形象爲中心而無需縮放是這樣的:當你設置一個的UIView的contentMode = 困惑NSImageView縮放

Just like iOS does when you set an UIView's contentMode = **UIViewContentModeCenter**

就像iOS的不UIViewContentModeCenter

所以我嘗試了所有NSImageScaling值,這是我所得到的當我選擇NSScaleNone

I really don't understand what's going on :-/

我真不明白這是怎麼回事: -/

回答

0

爲了得到你想要的結果,在圖像擴展到適合的觀點,您必須使用NSScaleToFit。這將改變照片的寬高比。

如果你想在相當於UIViewContentModeScaleAspectFill中,當圖像的寬高比保持不變,圖像被放大來填充空間,其溢出的區域進行修剪,然後看看這個傢伙的NSImage中類別:

http://rheard.com/blog/making-nsimages-resizable/

這可能是你想要的。

5

您可以手動生成正確大小和內容的圖像,並將其設置爲NSImageView的圖像,以便NSImageView無需執行任何操作。

NSImage *newImg = [self resizeImage:sourceImage size:newSize]; 
[aNSImageView setImage:newImg]; 

以下函數調整圖像的大小以適應新尺寸,保持縱橫比不變。如果圖像小於新尺寸,則放大並填充新圖像。如果圖像比新的大小,它是小型化,充滿了新的幀

- (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;} 
+1

如果你想要一個寬高比選項:[在這裏](https://github.com/spilliams/NSToolkit/blob/master/NSImage%2BResize.m)。 –

1

這裏是一個真棒類別NSImage中:NSImage+ContentMode

它允許內容模式,如在iOS上,偉大工程。

+0

非常好。 注意:您需要用'[NSGraphicsContext currentContext] .CGContext'替換MacOS的'UIGraphicsGetCurrentContext()'。 在CABasicAnimation期間High Sierra搞砸了NSImageView內容後特別有用 – codrut

+0

當h> w時,AspectFit無法正常工作。這是什麼工作: 'if(contentMode == UIViewContentModeScaleAspectFit){ \t \t \t CGSize imageSize = CGSizeMake(self.size.width,self.size。高度); \t \t \t CGSize containerSize = rect.size; \t \t \t \t \t \t CGFloat widthRaport = containerSize.width/imageSize.width; \t \t \t CGFloat heightRaport = containerSize.height/imageSize.height; \t \t \t CGFloat scale = MIN(widthRaport,heightRaport); \t \t \t \t \t \t imageSize.width = imageSize.width *規模; \t \t \t imageSize.height = imageSize.height * scale;'' – codrut

1

將圖像縮放屬性設置爲NSImageScaleAxesIndependently,這將縮放圖像以填充矩形。這不會保留寬高比。