Search code examples
swiftmacosnsimage

Resizing of NSImage not working


I am trying to resize a NSImage implementing a code that I got from this website https://gist.github.com/eiskalteschatten/dac3190fce5d38fdd3c944b45a4ca469, but it's not working.

Here is the code:

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)
    }

Solution

  • I forgot to calculate the ratio. Now it's working fine.

    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
        }