forum

Home / DeveloperSection / Forums / Problem in slicing an UIImage on iPhone

Problem in slicing an UIImage on iPhone

Tarun Kumar 2595 16-Sep-2015

Take a UIImage, crop out a square in the middle, change size of square to 320x320 pixels, slice up the image into 16 80x80 images, save the 16 images in an array.
Here's my code:

CGImageRef myImage, sizeImg, finalImg, tmp;
float widthImg, heightImg, diff;
UIImage *squareImg, *playImg;
NSMutableArray *arrayImgTitle;
int r, c;myImage = [image CGImage];

widthImg = image.size.width;
heightImg = image.size.height;
diff = fabs(widthImg - heightImg);

if(widthImg > heightImg) {
   sizeImg = CGImageCreateWithImageInRect(myImage,
             CGRectMake(floor(diff/2), 0, heightImg, heightImg));
} else {
   sizeImg = CGImageCreateWithImageInRect(myImage, CGRectMake(0,
             floor(diff/2), widthImg, widthImg));
}
CGImageRelease(myImage);

squareImg = [UIImage imageWithCGImage:sizeImg]; 
if(squareImg.size.width != squareImg.size.height) {
   NSLog(@"image cutout error!");
   //*code to return to main menu of app, irrelevant here
} else {
  float newDim = squareImg.size.width;
  if(newDim != 320.0) {
     CGSize finalSize = CGSizeMake(320.0, 320.0);
     UIGraphicsBeginImageContext(finalSize);
     [squareImg drawInRect:CGRectMake(0, 0, finalSize.width,
                           finalSize.height)];
     playImg = UIGraphicsGetImageFromCurrentImageContext();
     UIGraphicsEndImageContext();
  } else {
     playImg = squareImg;
  }
}

finalImg = [playImg CGImage];
arrayImgTitle = [NSMutableArray arrayWithCapacity:0];
for(int i = 0; i < 16; i++) {
   r = i/4;
   c = i%4;

   tmp = CGImageCreateWithImageInRect(finalImg, CGRectMake(c*tileSize,
         r*tileSize, tileSize, tileSize));
   [arrayImgTitle addObject:[UIImage imageWithCGImage:tmp]];
}

The code works correctly when the original (the variable image) has its smaller dimension either bigger or smaller than 320 pixels. When it's exactly 320, the resulting 80x80 images are almost entirely black, some with a few pixels at the edges that may (I can't really tell) be from the original image.

I tested by displaying the full image both directly:

[UIImage imageWithCGImage:finalImg];

And indirectly:

[UIImage imageWithCGImage:CGImageCreateWithImageInRect(finalImg, CGRectMake(0, 0, 320, 320))];

In both cases, the display worked. The problems only arise when I attempt to slice out some part of the image.


Updated on 17-Sep-2015

Can you answer this question?


Answer

1 Answers

Liked By