iOS Quick Tip: Split a UIImage into Multiple Parts

Stephen Zaharuk / Tuesday, May 27, 2014

Given a UIImage, in some cases you may want to have the image split. For example, say you wanted to create a Flipboard or Paper like interface, where you have a screen shot of a UIVIew, and you want to have the appearance of it folding. 

To do this you can use the CGImageCreateWithImageInRect method in objective-c. 

The code below is an example of how to use this method. In this scenario we're splitting the image in half, a left and right image. 

-(void)splitImage:(UIImage *)image
{
   CGFloat imgWidth = image.size.width/2;
   CGFloat imgheight = image.size.height;
   CGRect leftImgFrame = CGRectMake(0, 0, imgWidth, imgheight);
   CGRect rightImgFrame = CGRectMake(imgWidth, 0, imgWidth, imgheight);

  CGImageRef left = CGImageCreateWithImageInRect(image.CGImage, leftImgFrame);
  CGImageRef right = CGImageCreateWithImageInRect(image.CGImage, rightImgFrame);

  UIImage* leftImage = [UIImage imageWithCGImage:left];
  UIImage* rightImage = [UIImage imageWithCGImage:right];

  CGImageRelease(left);
  CGImageRelease(right);
}

To do this, we first figure out the clipping area we want for each image. In the case above, the left side will consist of an x of zero and  the width divided  by 2. While for the right image, we use the same width but make the x start at where the left image ended.

NOTE  You must release the CGImageRef when you're finished with it, otherwise there will be a memory leak.

Enjoy

By Stephen Zaharuk (SteveZ)