我的文档目录中有一个精灵表。精灵表由 256 个图标组成。
我有一个表格视图,其中我为每一行创建 3 个按钮,其中包含来自精灵表的切片部分的背景图像。
下面是从精灵中提取切片图标的代码。使用已知坐标
-(UIImage *)getSlicedImageForDictionary:(NSDictionary *)spriteInfoDictionary spriteImageRef:(UIImage *)spriteImageReference{
NSString *frameString = [spriteInfoDictionary objectForKey:@"frame"];
NSString *frameStringWithOnlyCommas = [[[frameString stringByReplacingOccurrencesOfString:@"\"" withString:@""] stringByReplacingOccurrencesOfString:@"{" withString:@""] stringByReplacingOccurrencesOfString:@"}" withString:@""];
NSArray *frameValues = [frameStringWithOnlyCommas componentsSeparatedByString:@","];
CGImageRef cgIcon = CGImageCreateWithImageInRect(spriteImageReference.CGImage, CGRectMake([[frameValues objectAtIndex:0] floatValue], [[frameValues objectAtIndex:1] floatValue], [[frameValues objectAtIndex:2] floatValue], [[frameValues objectAtIndex:3] floatValue]));
UIImage *icon = [UIImage imageWithCGImage:cgIcon];
frameString = nil;
frameStringWithOnlyCommas = nil;
frameValues = nil;
CGImageRelease(cgIcon);
return icon;
}
我在 for 循环中调用上述方法,如下所示,
for (int i = 0; i < [iconInfoArray count]; i ++) {
NSDictionary *currentBook = [spriteInfoDictionary objectForKey:[iconInfoArray objectAtIndex:i]];
articleMetaData.articleImage = [self getSlicedImageForDictionary:currentBook spriteImageRef:self.spriteImageSource];
[spriteIconsArray addObject:articleMetaData];
}
问题是, 当我从 spriteIconsArray 设置表格视图中的按钮时,我收到“收到内存警告”问题并且应用程序崩溃。
[btn setBackgroundImage:[spriteIconsArray objectAtIndex:i] forState:UIControlStateNormal];
但是当我将图像引用写入文档目录时,我没有收到任何内存警告并且应用程序运行顺利。
NSData *data = UIImagePNGRepresentation([spriteIconsArray objectAtIndex:i]);
NSString *pathOfTempImage = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"tempIcon.png"];
[data writeToFile:pathOfTempImage atomically:YES];
[btn setBackgroundImage:pathOfTempImage forState:UIControlStateNormal];
我很困惑为什么会这样。我不想将图像写入文档并再次读取,这可能会为大量数据产生一些延迟。
请在这方面给我建议。
谢谢