create UIImageView with portion of image file

iphone, uiimage, uiimageview

Solution

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);

Problem

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.

Original source