最近項目需要實現(xiàn)一個圖片瀏覽器的功能,要求也很常規(guī),如下:
1、具有彈出、收起動畫
2、在第N張圖片收起圖片瀏覽器時,容器內(nèi)容要求定位在該圖片的顯示位置
3、流暢
最終實現(xiàn)效果如下:
2016-12-29 14_37_37.gif
由于項目中的文章頁面使用H5渲染,所以解決思路如下:
1、js通知native所需要顯示的圖片url數(shù)組、index(當(dāng)前點擊的圖片索引)、rect(當(dāng)前點擊圖片的區(qū)域位置)
2、native在關(guān)閉圖片瀏覽器時,通知js當(dāng)前查看的圖片index(js根據(jù)index跳轉(zhuǎn)到網(wǎng)頁對應(yīng)位置),js回調(diào)native通知當(dāng)前圖片的rect(用于native播放收起動畫)
期間遇到一個問題:
native并沒有webview中已加載的圖片資源,所以彈出動畫難免出現(xiàn)加載過程,影響體驗
解決方案如下:
注冊NSURLProtocol,監(jiān)聽webview中所有的圖片請求,并用SDWebImage緩存,以url為key,搞定。
- (void)startLoading {
NSURLSession *session = [NSURLSession sharedSession];
NSMutableURLRequest *request = [self.request mutableCopy];
[NSURLProtocol setProperty:@(YES) forKey:kProtocolHandledKey inRequest:request];
__weak typeof(self) weakSelf = self;
self.sessionTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
return;
}
NSString *mimeType = response.MIMEType;
if ([mimeType hasPrefix:@"image"]) {
NSString *url = weakSelf.request.URL.absoluteString;
SDImageCache *cache = [SDImageCache sharedImageCache];
[cache storeImage:[UIImage imageWithData:data] forKey:url toDisk:NO];
}
[weakSelf.client URLProtocol:weakSelf didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowedInMemoryOnly];
[weakSelf.client URLProtocol:weakSelf didLoadData:data];
[weakSelf.client URLProtocolDidFinishLoading:weakSelf];
}];
[self.sessionTask resume];
}