2017-09-06 2 views
0

이 웹 사이트 https://gist.github.com/eiskalteschatten/dac3190fce5d38fdd3c944b45a4ca469에서 얻은 코드를 구현하는 NSImage의 크기를 조정하려고했지만 작동하지 않습니다.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

당신이 전달하는 타마 노가 아니라 자신의 크기로 이미지의 크기를 조정하는 것처럼 보입니다. – Abizern

답변

0

I의 비를 계산하는 것을 잊었 : 여기

코드이다. 이제 제대로 작동합니다.

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 
    } 
관련 문제