iPhone UIImageView задерживает отображение, когда setImage - PullRequest
0 голосов
/ 09 декабря 2011

Я работаю над отображением нескольких изображений в виде прокрутки, загруженном из MapServer, который возвращает изображение с отображением карты.Итак, я создал 4 UIImageViews и поместил их в NSMutableDictionary.Затем при прокрутке до нужного изображения он начнет загружать данные из URL-адреса асинхронно.поэтому сначала я отображаю UIActivityIndicatorView, затем он загружает данные и, в конце концов, скрывает UIActivityIndicatorView и отображает UIImageView.

все работает более или менее нормально, за исключением того, что для отображения изображения требуется слишком много времениНесмотря на то, что изображение не такое большое, и у меня есть текст журнала, указывающий, что пришел конец функции ... это сообщение журнала появляется сразу, но изображение по-прежнему не отображается ... Если я вызываю URL через веб-браузер, изображениесразу же показывается.

ниже вы видите мой кусок кода.

- (void) loadSRGImage:(int) page {

UIImageView *currentSRGMap   = (UIImageView *)[srgMaps objectForKey:[NSString stringWithFormat:@"image_%i", page]];
UIActivityIndicatorView *currentLoading  = (UIActivityIndicatorView *)[srgMaps objectForKey:[NSString stringWithFormat:@"loading_%i", page]];


// if the image has been loaded already, do not load again
if ( currentSRGMap.image != nil ) return;

if ( page > 1 ) {

    MKCoordinateSpan currentSpan;
    currentSpan.latitudeDelta   = [[[srgMaps objectForKey:[NSString stringWithFormat:@"span_%i", page]] objectForKey:@"lat"] floatValue];
    currentSpan.longitudeDelta  = [[[srgMaps objectForKey:[NSString stringWithFormat:@"span_%i", page]] objectForKey:@"lon"] floatValue];

    region.span         = currentSpan;
    region.center       = mapV.region.center;
    [mapV setRegion:region animated:TRUE];
    //[mapV regionThatFits:region];
}
srgLegende.hidden = NO;

currentSRGMap.hidden = YES;
currentLoading.hidden = NO;
[currentLoading startAnimating];

NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] 
                                    initWithTarget:self
                                    selector:@selector(loadImage:) 
                                    object:[NSString stringWithFormat:@"%i", page]];

[queue addOperation:operation]; 
[operation release];

}

- (void) loadImage:(NSInvocationOperation *) operation {

NSString *imgStr = [@"image_" stringByAppendingString:(NSString *)operation];
NSString *loadStr = [@"loading_" stringByAppendingString:(NSString *)operation];

WGS84ToCH1903 *converter = [[WGS84ToCH1903 alloc] init];

CLLocationCoordinate2D coord1   = [mapV convertPoint:mapV.bounds.origin toCoordinateFromView:mapV];
CLLocationCoordinate2D coord2   = [mapV convertPoint:CGPointMake(mapV.bounds.size.width, mapV.bounds.size.height) toCoordinateFromView:mapV];
int x1 = [converter WGStoCHx:coord1.longitude withLat:coord1.latitude];
int y1 = [converter WGStoCHy:coord1.longitude withLat:coord1.latitude];
int x2 = [converter WGStoCHx:coord2.longitude withLat:coord2.latitude];
int y2 = [converter WGStoCHy:coord2.longitude withLat:coord2.latitude];

NSString *URL = [NSString stringWithFormat:@"http://map.ssatr.ch/mapserv?mode=map&map=import/dab/maps/dab_online.map&mapext=%i+%i+%i+%i&mapsize=320+372&layers=DAB_Radio_Top_Two", y1, x1, y2, x2];

NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:URL]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
[imageData release];

UIImageView *currentSRGMap   = (UIImageView *)[srgMaps objectForKey:imgStr];
UIActivityIndicatorView *currentLoading  = (UIActivityIndicatorView *)[srgMaps objectForKey:loadStr];

currentSRGMap.hidden = NO;
currentLoading.hidden = YES;
[currentLoading stopAnimating];

[currentSRGMap setImage:image]; //UIImageView
[image release];

NSLog(@"finished loading image: %@", URL);

}

1 Ответ

0 голосов
/ 09 декабря 2011

У меня была похожая вещь в моем приложении, и я использовал SDWebImage из https://github.com/rs/SDWebImage.. Эта категория была записана более UIImageView. Вам нужно указать изображение-заполнитель и URL-адрес UIImageView. Он будет отображать изображение после его загрузки, а также будет поддерживать кэш загруженных изображений, что позволяет избежать многочисленных обращений к серверу.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...