0

我正在尝试使用 setImageFromURL 下载图像后获取图像的大小:

UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
[UIImageView setDefaultEngine:appDelegate.imageCache];
[img setImageFromURL:[NSURL URLWithString:@"http://testurl.com/testimg.jpg"]];
//img.frame = CGRectMake (0, 0, img.image.size.width, img.image.size.height);
[self.view addSubview:img];

我正在使用 MKNetworkKit - 有没有办法将完成处理程序添加到 setImageFromURL 方法?

4

2 回答 2

1

你可以自己申请completion block

很少评论,请使用Grand Central Dispatch来提高这种情况下的代码效率和多核利用率。

例子:

- (void) setImageFromUrl:(NSString*)urlString {  

    [self setImageFromUrl:urlString completion:NULL];  
}

- (void) setImageFromUrl:(NSString*)urlString   
              completion:(void (^)(void))completion {  

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{  

        NSLog(@"Starting: %@", urlString);  
        UIImage *avatarImage = nil;   
        NSURL *url = [NSURL URLWithString:urlString];  
        NSData *responseData = [NSData dataWithContentsOfURL:url];  
        avatarImage = [UIImage imageWithData:responseData];  
        NSLog(@"Finishing: %@", urlString);  

        if (avatarImage) {  
            dispatch_async(dispatch_get_main_queue(), ^{  
                self.image = avatarImage;  
                //Assign the image to ur ImageView.
                //get the image frame from ur ImageView.frame
            });  
            dispatch_async(dispatch_get_main_queue(), completion);  
        }  
        else {  
            NSLog(@"-- impossible download: %@", urlString);  
        }  
    });     
}  

更多详情,请访问iOS GCD 魔法

于 2013-05-23T04:00:59.760 回答
1

我可以通过添加这一行来做到这一点:

 self.frame = CGRectMake(0, 0, fetchedImage.size.width, fetchedImage.size.height);

到 UIImageView+MKNetworkKitAdditions.m:

if(imageCacheEngine) {
    self.imageFetchOperation = [imageCacheEngine imageAtURL:url
                   size:self.frame.size
      completionHandler:^(UIImage *fetchedImage, NSURL *url, BOOL isInCache) {

        self.frame = CGRectMake(0, 0, fetchedImage.size.width, fetchedImage.size.height);

        [UIView transitionWithView:self.superview
                          duration:isInCache?kFromCacheAnimationDuration:kFreshLoadAnimationDuration
                           options:UIViewAnimationOptionTransitionCrossDissolve | UIViewAnimationOptionAllowUserInteraction
                        animations:^{
                             self.image = fetchedImage;
                           } completion:nil];
          //[[NSNotificationCenter defaultCenter] postNotificationName:KW_IMAGE_LOADED object:nil];

      } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {

        DLog(@"%@", error);
      }];
  } else {

    DLog(@"No default engine found and imageCacheEngine parameter is null")
  }
于 2013-05-23T04:10:40.287 回答