Search code examples
objective-ccocoaxcodensimage

NSImage loading a portion of image


The requirement is like this, I would get a single large PNG Images for a button, this single image will contain images for hOver, button clicked , mouse exit that need to be displayed, Single PNG File size would be 1024 X 28, so each image have size about 256 X 28, I am googling the best possible approach but couldn't make out how to achieve this,

I have following approach in mind,

NSImage *pBtnImage[MAX_BUTTON_IMAGES]
for ( i = 0; i < 4 ; i++) {
pBtnImage[i] = [[NSImage alloc]initWithData:??????]; 
} 

I want to know what should i give in the NSData parameter,

Is it possible to load a Single Image and clipped image accordingly as and when it needed.

Thanks in advance


Solution

  • There's no simple Cocoa-supported way to read only a sub-rectangle of the image from its data. It's a simple matter, however, to read the whole image in and only use a select rectangle of the image when compositing. Thing is, with all the available API, you might be better off just to use the standard +[NSImage imageNamed:] method to read the images in individually and let the OS handle caching.

    What actual, measured performance problem are you trying to solve? Does one really exist, or is this a case of premature optimization?