gpt4 book ai didi

swift - 调整 NSImage 大小不起作用

转载 作者:行者123 更新时间:2023-11-30 12:10:52 24 4
gpt4 key购买 nike

我正在尝试调整 NSImage 的大小,该 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
}

关于swift - 调整 NSImage 大小不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46082965/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com