Search code examples
cocoansimage

Create a padded, centered, scaled NSImage


I'm putting a fixed size icon based on an arbitrarily sized image into an NSOutlineView using an NSImageCell.

NSImageCell will scale the image down nicely, but I can't find a way to add padding around the scaled image. The rows look ugly to my eye without padding.

My first pass at fixing this problem was to create a new image of constant size, inset its bounds for padding, then use drawInRect:fromRect:operation:fraction: to draw a scaled down version of the original icon.

That works great for square images. I would've guessed there'd be a convenience method on NSImage to draw a centered, scaled-with-constant-aspect-ratio version of the image in a given rect, but I can't find it.

Obviously I can calculate an appropriate rect with the same aspect ratio as the original image, but I'd rather not reinvent the wheel...


Solution

  • Every sample code I saw use a computation for the padding. There is some NSImage categories on CocoaDev that do that.