views:

32

answers:

1

I have an NSImage with different images inside it. The positions of the images inside of it will stay the same all the time, so I need to specify a rectangle to get a subimage at the position of the rectangle is inside of the image. How could this be done?

+2  A: 

Why are there multiple images inside of one image? Premature optimization?

In any case, when you draw the image, one of the parameters you pass is the section of the image you want. Normally, you pass either the bounds of the image or the zero rect (which both mean the same thing), but you can pass a subrectangle if you want.

If the destination rectangle is larger than the source rectangle, it will scale up (non-proportionally); if it's smaller, it will scale down (non-proportionally). Adjust the size of the destination rectangle to match that of the source rectangle if you don't want any scaling.

If you want to leave the drawing to an NSImageView, create an empty NSImage of the desired size, then draw into it, then pass that image to the image view. This probably destroys whatever performance advantage you'd hoped to gain by mashing these all together into one image.

You could also create a custom subclass of NSView, NSImageView, or CALayer that has a property for the NSImage and a property for the source rectangle, and draws only that section.

Peter Hosey