views:

708

answers:

2

Can any body explain me how an image can be (equally and unequally) split in to multiple parts in iPhone OS. It is very helpful to me if you provide sample code.

A: 

If you just want a region defined by an NSRect then this code should do it. If you need more complex regions (non-rectangular) then Apple's Cropped Image example includes code for cropping to a Bezier curve (see -croppedImage in CroppingImageView.m).

Naaff
+2  A: 

I have adapted some code I got out of Bill Dudney's Core Animation Book to accomplish this task:

- (NSArray*)splitImageIntoRects:(CGImageRef)anImage{

    CGSize imageSize = CGSizeMake(CGImageGetWidth(anImage), CGImageGetHeight(anImage));

 NSMutableArray *splitLayers = [NSMutableArray array];

 for(int x = 0;x < kXSlices;x++) {
  for(int y = 0;y < kYSlices;y++) {
   CGRect frame = CGRectMake((imageSize.width / kXSlices) * x,
                   (imageSize.height / kYSlices) * y,
                      (imageSize.width / kXSlices),
                   (imageSize.height / kYSlices));

   CALayer *layer = [CALayer layer];
   layer.frame = frame;             
   CGImageRef subimage = CGImageCreateWithImageInRect(drawnImage, frame);
   layer.contents = (id)subimage;
   CFRelease(subimage);
   [layers addObject:layer];
  }
    }
    return splitLayers; 
}

Note: To get an CGImageRef:

CGImageRef anImage = [myUIImage CGImage];
Corey Floyd