调整 NSImage 的大小不起作用

Resizing of NSImage not working

我正在尝试调整 NSImage 的大小,实现我从该网站 https://gist.github.com/eiskalteschatten/dac3190fce5d38fdd3c944b45a4ca469 获得的代码,但它不起作用。

代码如下:

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

我忘记计算比率了。现在一切正常。

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
    }