views:

686

answers:

1

I'm subclassing UIImageView to create a tile-based application. Essentially, I am taking a single image file and breaking it up into pieces, and then assigning the pieces to my tiles (UIImageViews), so that they can be manipulated independently.

What's the best way to grab a portion of an image and use that to draw a UIImageView? I thought about overriding drawRect and using CGAffineTransform, but it seems like there ought to be a simpler way to do this, perhaps by specifying a CGRect to the UIImage that is passed to the UIImageView, but I don't see an API for this.

+2  A: 

Here we go:

UIImage* img = [UIImage imageNamed:@"myImage.jpg"];
CGRect imgFrame = CGRectMake(x, y, tileWidth, tileHeight);
CGImageRef imageRef = CGImageCreateWithImageInRect([img CGImage], imgFrame);
UIImage* subImage = [UIImage imageWithCGImage: imageRef];
CGImageRelease(imageRef);
Caffeine Coma
Don't forget to release the imageRef after creating the UIImage: CGImageRelease(imageRef)
Nikolai Ruhe
fixed, thanks Nikolai
Caffeine Coma