我想在应用中使用一系列图像。我想要做的是将它们存储在NSArray中,以便在drawRect:function中轻松识别。
我创建了一个.plist文件,它详细说明了一个NSDictionary,其中的键只是提升整数值,以及与图像文件名对应的值。这允许我遍历字典并将一系列NSImage对象添加到数组中。我在这里使用for循环,因为顺序很重要,快速枚举不保证从字典中读取时的执行顺序!
目前我正在执行以下操作:(这是在NSView的子类中)
@property (strong) NSDictionary *imageNamesDict;
@property (strong) NSMutableArray *imageArray;
...
// in init method:
_imageNamesDict = [[NSDictionary alloc] initWithContentsOfFile:@"imageNames.plist"];
_imageArray = [[NSMutableArray alloc] initWithCapacity:[_imageNamesDict count]];
for (int i=0; i<_imageNamesDict.count; i++) {
NSString *key = [NSString stringWithFormat:@"%d", i];
[_imageArray addObject:[NSImage imageNamed:[_imageNamesDict objectForKey:key]];
}
// When I want to draw a particular image in drawRect:
int imageToDraw = 1;
// Get a pointer to the necessary image:
NSImage *theImage = [_imageArray objectAtIndex:imageToDraw];
// Draw the image
NSRect theRect = NSMakeRect (100,100, 0, 0);
[theImage drawInRect:theRect fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];
这一切似乎都能正常运行,但有一个怪癖。我注意到在绘制显示时会发生少量延迟,但仅限于第一次绘制新图像时。一旦每个图像至少被看过一次,我就可以重新绘制任何想要的图像而没有任何延迟。
是不是我没有正确加载图像,或者在创建要添加到for循环的对象时,是否有某些方法可以预先缓存每个图像?
谢谢!
答案 0 :(得分:2)
假设您已经克服了评论中指出的“... NSMutableDictionary而不是NSMutableArray ...”问题,那么您正在正确加载图像。
您所描述的滞后是因为[NSImage imageNamed: ]
没有完成所有绘制图像所需的工作,所以这是在第一次抽奖时发生的。
当您将图像添加到阵列时,可以通过将图像绘制到屏幕外缓冲区来消除滞后,例如:
// Create an offscreen buffer to draw in.
newImage = [[NSImage alloc] initWithSize:imageRect.size];
[newImage lockFocus];
for (int i=0; i<_imageNamesDict.count; i++) {
NSString *key = [NSString stringWithFormat:@"%d", i];
NSImage *theImage = [NSImage imageNamed:[_imageNamesDict objectForKey:key]];
[_imageArray addObject: theImage];
[theImage drawInRect:imageRect fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];
}
[newImage unlockFocus];
[newImage release];