2017-09-06 6 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

私は比率を計算するのを忘れていました。今それは正常に動作しています。

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 
    } 
関連する問題