Creating ICNS icon files from within Cocoa
Friday, March 20th, 2009I’ve been exploring how to let users set custom drive icons for ExpanDrive 2.0, and after spending quite a while googling for any information on a cocoa/carbon framework that would help me do this, it appears there are few resources available on making .icns files. This post doesn’t add a lot of value to the subject itself, but will hopefully send a few people in the right direction.
The easiest way to create a custom icon in your code is with the (hard to find) IconFamily project. It’s a great wrapper around Icon Services, with more than a little added convenience.
IconFamily lets you:
- create a multi-representation icon family from any arbitrary NSImage
- assign an icon family as a file or folder’s custom icon resource, so it will appear in Finder views
- read and write .icns files
- copy icon data to and from the scrap (pasteboard)
- get and set the elements of an icon family in convenient, Cocoa-compatible NSBitmapImageRep form
Here are a few short examples:
Create and write an ICNS file from a NSImage:
IconFamily* iconFamily = [IconFamily iconFamilyWithThumbnailsOfImage:someNSImage usingImageInterpolation:NSImageInterpolationHigh]; [iconFamily writeToFile:@"/Some/path/file.icns"];
If you don’t want to use interpolation to create your intermediate resolutions, it’s easy to set them by hand
- (BOOL) setIconFamilyElement:(OSType)elementType fromBitmapImageRep:(NSBitmapImageRep*)bitmapImageRep
There is also built in support for setting a custom icon for a particular file or directory, which is nice if you want to spam your logo on a few resources you’re associated with.
- (BOOL) setAsCustomIconForFile:(NSString*)path - (BOOL) setAsCustomIconForDirectory:(NSString*)path
Easy.


