2017-09-06 121 views
0

我想調整一個NSImage實現代碼,我從這個網站https://gist.github.com/eiskalteschatten/dac3190fce5d38fdd3c944b45a4ca469,但它不起作用的代碼。調整大小的NSImage不起作用

下面是代碼:

static func redimensionaNSImage(imagem: NSImage, tamanho: NSSize) -> NSImage { 

     var imagemRect: CGRect = CGRect(x: 0, y: 0, width: imagem.size.width, height: imagem.size.height) 
     let imagemRef = imagem.cgImage(forProposedRect: &imagemRect, context: nil, hints: nil) 

     return NSImage(cgImage: imagemRef!, size: tamanho) 
    } 
+0

當你說「它不工作」是什麼意思?你看到了什麼,你期望什麼? – Abizern

+0

這不是調整大小,圖像保持相同的大小。你看到我的代碼有問題嗎? – GuiDupas

+0

看起來你正在調整圖像的大小,而不是你通過的tamanho。 – Abizern

回答

0

忘了計算的比率。現在它工作正常。

static func redimensionaNSImage(imagem: NSImage, tamanho: NSSize) -> NSImage { 

     var ratio:Float = 0.0 
     let imageWidth = Float(imagem.size.width) 
     let imageHeight = Float(imagem.size.height) 
     let maxWidth = Float(tamanho.width) 
     let maxHeight = Float(tamanho.height) 

     // Get ratio (landscape or portrait) 
     if (imageWidth > imageHeight) { 
      // Landscape 
      ratio = maxWidth/imageWidth; 
     } 
     else { 
      // Portrait 
      ratio = maxHeight/imageHeight; 
     } 

     // Calculate new size based on the ratio 
     let newWidth = imageWidth * ratio 
     let newHeight = imageHeight * ratio 

     // Create a new NSSize object with the newly calculated size 
     let newSize:NSSize = NSSize(width: Int(newWidth), height: Int(newHeight)) 

     // Cast the NSImage to a CGImage 
     var imageRect:CGRect = CGRect(x: 0, y: 0, width: imagem.size.width, height: imagem.size.height) 
     let imageRef = imagem.cgImage(forProposedRect: &imageRect, context: nil, hints: nil) 

     // Create NSImage from the CGImage using the new size 
     let imageWithNewSize = NSImage(cgImage: imageRef!, size: newSize) 

     // Return the new image 
     return imageWithNewSize 
    } 
相關問題