如何将imageWithContentsOfFile用于动画中使用的图像数组?

时间:2011-10-25 09:00:45

标签: ios uiimage

这就是我目前所拥有的:

NSMutableArray *images = [[NSMutableArray alloc] initWithCapacity:21];

 for(int count = 1; count <= 21; count++)
{
    NSString *fileName = [NSString stringWithFormat:@"dance2_%03d.jpg", count];
    UIImage  *frame    = [UIImage imageNamed:fileName];
    [images addObject:frame];
}

UIImage imageNamed导致我一些内存问题,我想切换到imageWithContentsOfFile。

我可以使用单个图像,但不是整个数组:

NSMutableArray *images = [[NSMutableArray alloc] initWithCapacity:21];

for(int count = 1; count <= 21; count++)
{
    NSString *fileName = [[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"/dance2_001.jpg"];
    UIImage  *frame    = [UIImage imageWithContentsOfFile:fileName];
    [images addObject:frame];
}

非常感谢任何帮助!谢谢!

2 个答案:

答案 0 :(得分:5)

for(int i = 1; i <= 21; i++)
    {
        [images addObject:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"dance2_%03d", i] ofType:@"jpg"]]];
    }

答案 1 :(得分:1)

首先应该做的是创建一个包含动画图像的数组,如下所示:

NSMutableArray* images = [[NSMutableArray alloc] initWithObjects:
                             [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"image1" ofType:@"jpg"]],
                             [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"image2" ofType:@"jpg"]],
                             nil];

然后你可以将它添加到UIImageView来为它设置动画:

UIImageView* animationImagesView = [[UIImageView alloc] initWithFrame:CGRectMake(posX, posY, frameWidth, frameHeight)]; 
animationImagesView.animationImages = images; //array of images to be animate
animationImagesView.animationDuration = 1.0; //duration of animation
animationImagesView.animationRepeatCount = 1; //number of time to repeat animation
[self.view addSubview:animationImagesView];

现在您可以使用以下两个调用来启动和停止动画:

[animationImagesView startAnimating]; //starts animation 
[animationImagesView stopAnimating]; //stops animation
希望这会有所帮助。还记得在完成后释放你的Array和UIImageView。