【问题标题】:How to add UIImages to an NSMutableArray, and change the images later?如何将 UIImages 添加到 NSMutableArray,并稍后更改图像?
【发布时间】:2011-05-15 01:18:55
【问题描述】:

我正在制作一个简单的游戏,需要在许多不同的地方绘制多个 UIImage。我的问题是我需要将 UIImages 添加到 NSMutableArray,然后再访问它们。使用 NSStrings 来表示图像(例如路径)在这里不起作用,所以我需要知道如何更改数组中每个 UIImage 的图像。

我的代码如下(至少,用于访问 NSMutableArray)。 NSMutableArray 在我的 .h 文件中声明,并以不同的方法初始化。

for (int a = 0; a <= [theArray count]; a ++) {
    // I make a UIImage, which I will draw later
    UIImage *theImage = [theArray objectAtIndex:a];
    // then I do the drawing
}

这很好用。我的问题是我无法弄清楚如何更改 NSMutableArray 中的特定对象。我该怎么做?

顺便说一句,我正在使用以下代码将 UIImages 添加到 NSMutableArray。

+ (void) createCarWithImage:(NSString*)theImageName {
    UIImage *anImage= [UIImage imageNamed:theImageName];
    [theArray addObject:anImage];
}

【问题讨论】:

    标签: objective-c cocoa-touch uiimage nsmutablearray


    【解决方案1】:

    我想你想用这个方法:

    - (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject
    

    例如:

    [theArray replaceObjectAtIndex:4 withObject:someOtherImage];
    

    【讨论】:

      【解决方案2】:

      只需按原样修改NSMutableArray 中的每个UIImage,您只有一个指向实际数据的指针。也就是说,不管你用什么指针来改变数据,每一个指针都会改变数据。

      此外,您还可以使用以下命令遍历您的 UIImages:

      for (UIImage *img in theArray)
      {
           //send messages to img
      }
      

      回复评论

      您可以通过以下方式修改索引 4 处的 UIImage

      UIImage *image = [theArray objectAtIndex:4];
      //send messages to image
      

      【讨论】:

      • 如何修改图片?那是我的问题,但这个答案并没有告诉我怎么做。
      • 通过发送UIImage 响应的每个图像消息来修改它。您是在寻找缩放、翻译等,还是在寻找逐像素修改?
      • 我不认为我们在这里相互理解。如何在不使用 for 循环的情况下更改图像?例如,如果我想修改索引@“4”处的图像,我需要做什么?
      • 我更新了我的答案以回答您当前的问题。就修改而言,它就像操作任何其他对象一样。您向它发送消息,它会响应。
      猜你喜欢
      • 2011-10-28
      • 2020-04-22
      • 2010-09-08
      • 2014-05-25
      • 1970-01-01
      • 2011-12-13
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      相关资源
      最近更新 更多