将 NSImage 放置在 Swift 中的透明 canvas 上

Placing an NSImage on a transparent canvas in Swift

我正在寻找一种创建 NSImage 的方法,方法是将现有图像放在 Swift 中的透明 canvas 上。例如,这将是一个函数,可以将 200 x 300 的 NSImage 和 return 作为 300 x 300 的 NSImage(两边有 50 像素的透明 canvas)。

我找到了这个 用于 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))
    }

这让我可以使用 "crop" 函数将 canvas 扩展到所需的大小,而不是裁剪图像。