Matt Gemmell

My new book CHANGER is out now!

An action-adventure novel — book 1 in the KESTREL series.

★★★★★ — Amazon

ImageCrop source code

Development & Source 1 min read

A trivial piece of code, but one I often find myself in need of.

NSImage+MGCropExtensions is a category on NSImage which lets you obtain a version of the image scaled to a specified size (using high-quality interpolation), via a choice of four methods:

  • Crop (Center) - proportionally scale the image to fit the appropriate dimension of the target size, and then center-cropped to produce the required size.
  • Crop Start - as for Crop, but cropped at the "start" of the image, i.e. either the top or left, depending on the relative aspect-ratios of the source image and the target size.
  • Crop End - as for Crop Start, but using the "end" of the image, i.e. the bottom or right.
  • Scale to Fit - proportionally scale the image to fit entirely within the target size, leaving transparency around it if necessary.

If that sounds complicated, just download the source code and try out the included sample app; it’ll all make sense. Useful when you want to make an arbitrary image fit into an arbitrary region, either with or without space around the resulting image. You can also take a look at a screenshot, as usual. Find more code on my Cocoa Source Code page.