例如,png文件是1200(h)x 50(w)像素,我怎样才能切割 png并加载6 UIImage
s,每个200(h) x 50(w)。谢谢!
编辑 - 感谢Michal的回答,最终代码:
CGImageRef imageToSplit = [UIImage imageNamed:@"huge.png"].CGImage;
CGImageRef partOfImageAsCG = CGImageCreateWithImageInRect(imageToSplit, CGRectMake(0, 0, 50, 50));
UIImage *partOfImage = [UIImage imageWithCGImage:partOfImageAsCG];
// ...
CGImageRelease(partOfImageAsCG);
答案 0 :(得分:13)
查看CGImageCreateWithImageInRect函数。它适用于CGImage,但很容易在那个和UIImage之间进行转换。
这是一个例子(从内存中输入,可能无法编译):
CGImageRef imageToSplit = [UIImage imageNamed:@"huge.png"].CGImage;
CGImageRef partOfImageAsCG = CGImageCreateWithImageInRect(imageToSplit, CGRectMake(0, 0, 200, 50));
CGRelease(imageToSplit);
UIImage *partOfImage = [UIImage imageWithCGImage:partOfImageAsCG];
CGImageRelease(partOfImageAsCG);
答案 1 :(得分:2)
可重复使用的方法:
-(UIImage*)ExtractImageOn:(CGPoint)pointExtractedImg ofSize:(CGSize)sizeExtractedImg FromSpriteSheet:(UIImage*)imgSpriteSheet
{
UIImage *ExtractedImage;
CGRect rectExtractedImage;
rectExtractedImage=CGRectMake(pointExtractedImg.x,pointExtractedImg.y,sizeExtractedImg.width,sizeExtractedImg.height);
CGImageRef imgRefSpriteSheet=imgSpriteSheet.CGImage;
CGImageRef imgRefExtracted=CGImageCreateWithImageInRect(imgRefSpriteSheet,rectExtractedImage);
ExtractedImage=[UIImage imageWithCGImage:imgRefExtracted];
CGImageRelease(imgRefExtracted);
//CGImageRelease(imgRefSpriteSheet); I have commented it because
// we should not release the object that we don't own.
// So why do we release imgRefExtracted alone? because it has
// name create in its method so the ownership comes to us so we
// have to release it.
return ExtractedImage;
}
供参考:
即使已经清楚地回答了我的想法,我认为将它作为简单的可重复使用的“复制粘贴”代码片段对程序员来说会有很多帮助,我将答案归结为michal