how to crop image in to pieces programmatically

The code below is also a solution that detects the piece of the picture that was tapped on. The idea is to take a UIImage and use CGImageCreateWithImageInRect to crop out pieces. From the cropped piece create a new UIImage and place it in a UIImageView. In order to get the tap gesture to work I had to place the UIImageView in a UIView. Finally, provide the gesture and a unique tag so that the piece can be identified when tapped on.

- (void)loadView {
    UIView* root = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
    UIImage* whole = [UIImage imageNamed:@"whole.jpg"]; //I know this image is 300x300

    int partId = 0;
    for (int x=0; x<=200; x+=100) {
        for(int y=0; y<=200; y+=100) {
            CGImageRef cgImg = CGImageCreateWithImageInRect(whole.CGImage, CGRectMake(x, y, 100, 100));
            UIImage* part = [UIImage imageWithCGImage:cgImg];
            UIImageView* iv = [[UIImageView alloc] initWithImage:part];

            UIView* sView = [[UIView alloc] initWithFrame:CGRectMake(200-x, 200-y, 100, 100)];
            [sView addSubview:iv];
            [iv release];

            UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                  action:@selector(tap:)];
            tap.numberOfTapsRequired = 1;
            [sView addGestureRecognizer:tap];
            [tap release];

            sView.tag = partId;

            [root addSubview:sView];
            [sView release];
            partId++;
            CGImageRelease(cgImg);
        }
    }

    self.view = root;
}

- (void)tap:(UITapGestureRecognizer*)gesture
{
    NSLog(@"image tap=%d", gesture.view.tag);
}

Leave a Comment