gpt4 book ai didi

swift - 在 Swift 中将 NSImage 放置在透明 Canvas 上

转载 作者:行者123 更新时间:2023-11-30 11:53:04 25 4
gpt4 key购买 nike

我正在寻找一种通过将现有图像放置在 Swift 中的透明 Canvas 上来创建 NSImage 的方法。例如,它是一个可以获取 200 x 300 NSImage 并将其作为 300 x 300 NSImage 返回的函数(两侧各有 50 px 的透明 Canvas )。

我发现了这个 this适用于 iOS,但我不知道如何将其转换为 macOS。

我不知道它会有什么用,但这是我已经开始研究的一个扩展:

extension NSImage {
func squareIt(canvasSize: CGSize)->NSImage {
var imageToReturn:NSImage!

//make a CGRect with desired size
let rect = CGRect(origin: .zero, size: canvasSize)

//Center and draw image
let centeredImageRect = CGRect(x: (canvasSize.width - self.size.width) / 2,
y: (canvasSize.height - self.size.height) / 2,
width: self.size.width,
height: self.size.height)

self.draw(in: centeredImageRect)

//???? Place the original image in the rect and return the result as an NSImage

return imageToReturn

}

如果有人能指出我正确的方向,我将非常感激。

最佳答案

经过大量的挖掘,我终于能够在发布的 NSImage 扩展集中找到解决方案 here .

我所要做的就是修改“resizeWhileMaintainingAspectRatioToSize”函数,通过替换将图像保持在指定大小的范围内:

if widthRatio > heightRatio {
newSize = NSSize(width: floor(self.width * widthRatio), height: floor(self.height * widthRatio))
} else {
newSize = NSSize(width: floor(self.width * heightRatio), height: floor(self.height * heightRatio))
}

对于:

if widthRatio > heightRatio {
newSize = NSSize(width: floor(self.width * heightRatio), height: floor(self.height * heightRatio))
} else {
newSize = NSSize(width: floor(self.width * widthRatio), height: floor(self.height * widthRatio))
}

这使我能够使用“裁剪”功能将 Canvas 扩展到所需的尺寸,而不是裁剪图像。

关于swift - 在 Swift 中将 NSImage 放置在透明 Canvas 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48137111/

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