在Swift中的透明画布上放置NSImage

时间:2018-01-07 12:29:53

标签: swift macos nsimage

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

我找到了这个 适用于iOS的this,但我无法弄清楚如何将其转换为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

}

如果有人能指出我正确的方向,我真的很感激。

1 个答案:

答案 0 :(得分:0)

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

我所要做的就是修改“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))
    }

这允许我使用“裁剪”功能将画布扩展到所需的大小,而不是裁剪图像。