代码之家  ›  专栏  ›  技术社区  ›  GuiDupas

NSImage的大小调整不工作

  •  0
  • GuiDupas  · 技术社区  · 7 年前

    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)
        }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   GuiDupas    7 年前

    我忘了计算比率。现在它工作得很好。

    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
        }