views:

587

answers:

2

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?

+1  A: 

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://iphonedevelopertips.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];

}
Brock Woolf
This is great stuff and I'll definitely bookmark it but I don't want to create a mask for this. I simply want to do something like: [[UIImage imageNamed:@"myimage"] drawInRect:CGMakeRect(10,10,50,50) fromRect:CGMakeRect(60,60,50,50)];
rein
+2  A: 

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

Sixten Otto
Thanks, trying this now.
rein
Good one @Sixten, I think this sounds more like what he wanted +1
Brock Woolf
Works perfectly (minus some headaches with CGImages being flipped while drawing). Thanks.
rein