Question

I have a UIImage containing an image with a whole bunch of smaller pictures on the image (essentially an image strip containing sprites). I'd like to draw a single sprite onto an area of my UIView.

I can't seem to find a way draw only part of the UIImage onto the view. Is there a method that does this?

Was it helpful?

Solution

I think you may be looking for CGImageCreateWithImageInRect(). You can get a CGImage from a UIImage with the property of the same name.

EDIT: another option that exists in 2014, that did not in 2009, is SpriteKit. Depending on what you might be doing that needs a sprite sheet, that might be useful.

OTHER TIPS

I wrote a UIImage category for handling sprite sheets. Check this out, it may be helpful http://reecon.wordpress.com/2011/11/19/uiimage-sprite-additions-objective-c/

As noted earlier, this category bases on CGImageCreateWithImageInRect() but makes the process of extracting sprites from a single sprite sheet far more convenient and faster.

Link to git hub page: https://github.com/r3econ/UIImage-Sprite-Additions

You can also install using cocoa pods.

Yep, you sure can with Quartz.

There is a tutorial here that shows you how to take a UIImage and mask a part of it.

http://iosdevelopertips.com/cocoa/how-to-mask-an-image.html

Here is the code from that page (incase it goes down for some reason)

- (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage {

    CGImageRef maskRef = maskImage.CGImage; 

    CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
        CGImageGetHeight(maskRef),
        CGImageGetBitsPerComponent(maskRef),
        CGImageGetBitsPerPixel(maskRef),
        CGImageGetBytesPerRow(maskRef),
        CGImageGetDataProvider(maskRef), NULL, false);

    CGImageRef masked = CGImageCreateWithMask([image CGImage], mask);
    return [UIImage imageWithCGImage:masked];

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top