Alex Bonta
Alex Bonta

Reputation: 101

How to programmatically slice an image in 4 , 9 , 16 and 25 slices

i need a little help to slice a picture programatically in 4 , 9 ,16 and 25 slices

I would appreciate any help or idea . Thanks

Upvotes: 0

Views: 874

Answers (2)

Bouabane Mohamed Salah
Bouabane Mohamed Salah

Reputation: 527

Here is an example :

CGRect rect = CGRectMake(size.width / 4, size.height / 4 , 
(size.width / 2), (size.height / 2));
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
UIImage *img = [UIImage imageWithCGImage:imageRef]; 
CGImageRelease(imageRef);

And check out these links : Cropping and resizing image CGImage Reference

Upvotes: 0

bpolat
bpolat

Reputation: 3908

I made a simple app for this purpose. You can download from here:

https://github.com/bpolat/Image-Slicer

The code you require is:

-(NSMutableArray *)getImagesFromImage:(UIImage *)image withRow:(NSInteger)rows   withColumn:   (NSInteger)columns
 {
NSMutableArray *images = [NSMutableArray array];
CGSize imageSize = image.size;
CGFloat xPos = 0.0, yPos = 0.0;
CGFloat width = imageSize.width/rows;
CGFloat height = imageSize.height/columns;
for (int y = 0; y < columns; y++) {
    xPos = 0.0;
    for (int x = 0; x < rows; x++) {

        CGRect rect = CGRectMake(xPos, yPos, width, height);
        CGImageRef cImage = CGImageCreateWithImageInRect([image CGImage],  rect);

        UIImage *dImage = [[UIImage alloc] initWithCGImage:cImage];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(x*width, y*height, width, height)];
        [imageView setImage:dImage];
        [imageView.layer setBorderColor:[[UIColor blackColor] CGColor]];
        [imageView.layer setBorderWidth:1.0];
        [self.view addSubview:imageView];
        [images addObject:dImage];
        xPos += width;
    }
    yPos += height;
}
return images;
  }

Usage:

[self getImagesFromImage:[UIImage imageNamed:@"1.png"] withRow:4 withColumn:4];

Result:

enter image description here

Upvotes: 2

Related Questions