0

I am looking for a way to create an NSImage by placing an existing image on a transparent canvas in Swift. For example, it would be a function that could take a 200 x 300 NSImage and return it as a 300 x 300 NSImage (with 50 px of transparent canvas on either side).

I found this this for iOS, but I cannot figure out how to translate it over to macOS.

I don't know that it will be of any use, but here is an extension I've begun work on:

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

}

I would really appreciate it if anyone could point me in the right direction.

kamisama42
  • 595
  • 4
  • 18

1 Answers1

0

After a ton of digging around, I was finally able to find out a solution in the set of NSImage extensions posted here.

All I had to do was to modify the "resizeWhileMaintainingAspectRatioToSize" function to keep the image within the bounds of the specified size by substituting:

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))
    }

for:

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))
    }

This allowed me to use the "crop" function to expand the canvas to the desired size rather than cropping the image.

kamisama42
  • 595
  • 4
  • 18