使用AFNetworking,从服务器下载图像并放入UIImageView非常简单:
[imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]];
如果我想用效果(可能是淡入淡出)替换图像怎么样?
这是因为我想用很多图片制作幻灯片。
答案 0 :(得分:45)
您可以将animateWithDuration
与提供setImageWithURL
块的success
的再现结合使用,例如
[imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"]
placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
self.imageView.alpha = 0.0;
self.imageView.image = image;
[UIView animateWithDuration:0.25
animations:^{
self.imageView.alpha = 1.0;
}];
}
failure:NULL];
或者,如果占位符图片不是空白,您可能希望通过transitionWithView
进行解散:
[imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"]
placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
[UIView transitionWithView:self.imageView
duration:0.3
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
self.imageView.image = image;
}
completion:NULL];
}
failure:NULL];
更新
顺便说一句,如果您担心图像视图(如果您引用self
,视图或视图控制器)被保留直到下载完成,您可以:
__weak UIImageView *weakImageView = self.imageView;
[imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"]
placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
UIImageView *strongImageView = weakImageView; // make local strong reference to protect against race conditions
if (!strongImageView) return;
[UIView transitionWithView:strongImageView
duration:0.3
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
strongImageView.image = image;
}
completion:NULL];
}
failure:NULL];
即使您这样做,图像视图也会保留,直到下载完成,因此您也可以选择取消视图控制器的dealloc
方法中正在进行的任何下载:
- (void)dealloc
{
// if MRC, call [super dealloc], too
[_imageView cancelImageRequestOperation];
}
答案 1 :(得分:3)
当在线请求成功完成时,尝试将imageView的alpha设置为0到1的动画:
// You should not call an ivar from a block (so get a weak reference to the imageView)
__weak UIImageView *weakImageView = self.imageView;
// The AFNetworking method to call
[imageView setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://host.com/image1.png"]] placeholderImage:nil]
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image){
// Here you can animate the alpha of the imageview from 0.0 to 1.0 in 0.3 seconds
[weakImageView setAlpha:0.0];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
[weakImageView setAlpha:1.0];
[UIView commitAnimations];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){
// Your failure handle code
}
当然,您可以在完成区内使用您喜欢的任何其他动画!