目标:取一个UIImage,在中间裁剪出一个正方形,将正方形的大小改为320x320像素,将图像切割成16个80x80图像,将16个图像保存在一个数组中.
这是我的代码:
CGImageRef originalImage, resizedImage, finalImage, tmp; float imgWidth, imgHeight, diff; UIImage *squareImage, *playImage; NSMutableArray *tileImgArray; int r, c; originalImage = [image CGImage]; imgWidth = image.size.width; imgHeight = image.size.height; diff = fabs(imgWidth - imgHeight); if(imgWidth > imgHeight){ resizedImage = CGImageCreateWithImageInRect(originalImage, CGRectMake(floor(diff/2), 0, imgHeight, imgHeight)); }else{ resizedImage = CGImageCreateWithImageInRect(originalImage, CGRectMake(0, floor(diff/2), imgWidth, imgWidth)); } CGImageRelease(originalImage); squareImage = [UIImage imageWithCGImage:resizedImage]; if(squareImage.size.width != squareImage.size.height){ NSLog(@"image cutout error!"); //*code to return to main menu of app, irrelevant here }else{ float newDim = squareImage.size.width; if(newDim != 320.0){ CGSize finalSize = CGSizeMake(320.0, 320.0); UIGraphicsBeginImageContext(finalSize); [squareImage drawInRect:CGRectMake(0, 0, finalSize.width, finalSize.height)]; playImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); }else{ playImage = squareImage; } } finalImage = [playImage CGImage]; tileImgArray = [NSMutableArray arrayWithCapacity:0]; for(int i = 0; i < 16; i++){ r = i/4; c = i%4; //* tmp = CGImageCreateWithImageInRect(finalImage, CGRectMake(c*tileSize, r*tileSize, tileSize, tileSize)); [tileImgArray addObject:[UIImage imageWithCGImage:tmp]]; }
当原始(可变图像)的较小尺寸大于或小于320像素时,代码可正常工作.当它恰好是320时,得到的80x80图像几乎全部是黑色的,有些像素边缘可能(我无法分辨)可能来自原始图像.
我通过直接显示完整图像进行测试:
[UIImage imageWithCGImage:finalImage];
间接地:
[UIImage imageWithCGImage:CGImageCreateWithImageInRect(finalImage, CGRectMake(0, 0, 320, 320))];
在这两种情况下,显示都有效.只有当我试图切出图像的某些部分时才会出现问题.
经过一些更多的实验,我发现了以下解决方案(我仍然不知道为什么它不像最初编写的那样工作.)但是无论如何,即使在不需要调整大小的情况下,调整大小代码之后的切片也会起作用:
if(newDim != 320.0){ CGSize finalSize = CGSizeMake(320.0, 320.0); UIGraphicsBeginImageContext(finalSize); [squareImage drawInRect:CGRectMake(0, 0, finalSize.width, finalSize.height)]; playImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); }else{ CGSize finalSize = CGSizeMake(320.0, 320.0); UIGraphicsBeginImageContext(finalSize); [squareImage drawInRect:CGRectMake(0, 0, finalSize.width, finalSize.height)]; playImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); }
任何人都有任何线索为什么会这样?
PS是的,如果此处不再需要/ else.然而,在我知道它将起作用之前删除它将是愚蠢的.