2012-04-17 75 views
1

我需要以2秒的时间间隔在图像视图中显示图像。但是,此代码仅显示最后一张图片如何在循环中显示图像(来自网页)?

NSUInteger i,j; 
for (i = 1; i <= kNumImages; i++) 
{ 
    NSURL *picUrl=[NSURL URLWithString:[NSString stringWithFormat:@"http://panagtakdo.com/misc/images/%d.jpg",i]]; 
    NSData *picData=[[NSData alloc] initWithContentsOfURL:picUrl]; 
    image1.image = [UIImage imageWithData:picData]; 
    NSLog(@"Image %d Success",i); 
    [NSThread sleepForTimeInterval:0.2];  
} 

回答

1

首先,您不应该这样做。首先创建NSMutableArray * imageData;

和initWithContentsOfURL所有图像;

当imageData的数量等于你的kNumImages链接到你的imageView。而不是使用NSThread sleepForTimeInterval,你可以使用performSelector:afterDelay函数来改变图像。

0

如果你想显示图像的动画序列,您可以创建一个UIImage,不只是说:

NSMutableArray *mImageArray = [NSMutableArray arrayWithCapacity:0]; 
for(int i = 1; i < 9; i++) { 
    NSString *imageFileName = [NSString stringWithFormat:@"0%d.tiff",i]; 
    UIImage *newImage = [UIImage imageNamed:imageFileName]; 
    [mImageArray addObject:newImage]; 
} 

UIImage *animatedSequence = [UIImage animatedImageWithImages:mImageArray duration:16]; 

UIImageView *uiiv = [[UIImageView alloc] initWithImage:animatedSequence]; 
[self.canvas addSubview:uiiv]; 

您可以通过设置的UIImage的持续时间来控制图像的时间。我将持续时间设置为16秒,这会变成2秒/图像,因为我在我的序列中使用了8张图像。

(在ios模拟器中测试过它,它工作得很好)

P.S.在我的项目结构,self.canvas指主要的UIView

1

如果只想解释一下,为什么你的代码是工作:

你的线程休眠设置图像之后。没有时间重新绘制imageview(这会导致显示新图像)。因此,在所有循环运行之后,第一次重绘将会发生。所以你只能看到最后一张图片。

如果你结合了Travis和mhunturk的答案,你应该如何完成这个完美的解决方案。 但我也建议使用异步方法,从url加载图像。

你应该从来没有阻止主UI线程。无论是直接调用sleepForTimeInterval还是同步加载网页内容。

+0

非常感谢你..... – Manohar 2012-04-19 10:23:09

+0

如果你喜欢这个答案,你应该接受它:http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-工作 – calimarkus 2012-04-19 11:59:01

+0

谢谢............ – Manohar 2012-06-28 06:51:14