gpt4 book ai didi

arrays - 这是实现 NSImage 数组的合适方法吗?

转载 作者:行者123 更新时间:2023-12-03 17:41:12 24 4
gpt4 key购买 nike

我有一系列图像想要在应用程序中使用。我想要做的是将它们存储在 NSArray 中,以便在 drawRect: 函数中轻松识别。

我创建了一个 .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 循环的对象时预先缓存每个图像?

谢谢!

最佳答案

假设您已经克服了评论中指出的“... 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];

关于arrays - 这是实现 NSImage 数组的合适方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13905716/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com