我有一個屏幕,將加載大約5個圖像,但它們是巨大的圖像。現在,我使用從URL加載圖像,但逐步顯示它
NSURLRequest
和:
connectionDidFinishLoading
..for回調加載每個圖像的時候告訴我。
問題是圖像會一個接一個彈出。有沒有辦法在加載時顯示圖像?
感謝
我有一個屏幕,將加載大約5個圖像,但它們是巨大的圖像。現在,我使用從URL加載圖像,但逐步顯示它
NSURLRequest
和:
connectionDidFinishLoading
..for回調加載每個圖像的時候告訴我。
問題是圖像會一個接一個彈出。有沒有辦法在加載時顯示圖像?
感謝
顯示它在裝載時,我不認爲UIImageView
可以加載UIImages
不完整的數據,同時loading.I會去 AsyncImageView, 它能夠處理圖像加載所有的負擔asynchronous.Also UIActivityIndicator
已添加到它。因此它將更加用戶友好
使用塊和GCD的dispatch_async方法。
請看下面的例子:
//communityDetailViewController.h
@interface communityDetailViewController:的UIViewController {
UIImageView *imgDisplay;
UIActivityIndicatorView *activity;
// the dispatch queue to load images
dispatch_queue_t queue;
}
@end
//communityDetailViewController.m
- (void)loadImage
{
[activity startAnimating];
NSString *url = @"URL the image";
if (!queue) {
queue = dispatch_queue_create("image_queue", NULL);
}
dispatch_async(queue, ^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
UIImage *anImage = [UIImage imageWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
[activity stopAnimating];
activity.hidden = YES;
if (anImage != nil) {
[imgDisplay setImage:anImage];
}else{
[imgDisplay setImage:[UIImage imageNamed:@"no_image_available.png"]];
}
});
});
}
我需要它在加載時顯示它是否下載單個圖像的一半,它將顯示一半等等。我不認爲這是真的。我已經知道如何在不阻塞的情況下下載它,只是我需要它在下載時部分顯示。 – mskw
,你需要做到這一點可作爲CGImageSource方法是什麼膽量。
首先,您使用異步NSURLConnection來獲取數據。您將收到的數據添加到NSMutableData對象到達時,所以數據對象變得越來越大,直到完成。
您還可以創建逐行掃描的圖像來源:
CGImageSourceRef imageSourcRef = CGImageSourceCreateIncremental(dict);
您將在這裏和谷歌如何設置所需字典找到很多例子。
然後作爲數據到達時,傳遞的總數據對象插入此方法:
CGImageSourceUpdateData(imageSourcRef, (__bridge CFDataRef)data, NO); // No means not finished
然後可以要求一個圖像,作爲圖像正在下載這將是部分的圖像源。用CGImage你可以創建一個UIImage。
當你最終的數據,你就更新一次圖像源:
CGImageSourceUpdateData(imageSourcRef, (__bridge CFDataRef)data, YES);
然後,您使用的圖像源得到的最終圖像就大功告成了。
您可以繼承UIImageView
並使用它。
-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response
{
imageData = [NSMutableData data];
imageSize = [response expectedContentLength];
imageSource = CGImageSourceCreateIncremental(NULL);
}
-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
[imageData appendData:data];
CGImageSourceUpdateData(imageSource, (__bridge CFDataRef)imageData, ([imageData length] == imageSize) ? true : false);
CGImageRef cgImage = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
if (cgImage){
UIImage* img = [[UIImage alloc] initWithCGImage:cgImage scale:1.0f orientation:UIImageOrientationUp];
dispatch_async(dispatch_get_main_queue(), ^{
self.image = img;
});
CGImageRelease(cgImage);
}
}
我需要它在加載時顯示,如果它下載單個圖像的一半,它將顯示一半等等。我不認爲這是真的。我已經知道如何在不阻塞的情況下下載它,只是我需要它在下載時部分顯示。 – mskw