codecamp

Weex 加载 .xcassets 中的图片资源

背景

因为 .xcassets 中的图片资源只能通过 imageNamed: 方法加载,所以需要做一些特殊处理,才能提供给 Weex 使用(PS:纯属娱乐,因为 Weex 跨平台的特性,这种针对某一端做实现的方案实用价值并不大)。

方案

观察 WeexSDK 发现有 WXImgLoaderProtocol 这个协议,这个协议包含了下面的方法:

- (id<WXImageOperationProtocol>)downloadImageWithURL:(NSString *)url imageFrame:(CGRect)imageFrame userInfo:(NSDictionary *)options completed:(void(^)(UIImage *image,  NSError *error, BOOL finished))completedBlock;

从名字就可以看出来,这个方法声明的功能就是通过指定的 URL 下载图片并返回一个 UIImage 对象。

下载过 WeexDemo 的人应该都知道里面有一个叫 WXImgLoaderDefaultImpl 的类(PS:别告诉我你对 Weex 感兴趣确连 WeexDemo 里面有啥都不知道)。这个类实现了 WXImgLoaderProtocol 协议,内容如下:

- (id<WXImageOperationProtocol>)downloadImageWithURL:(NSString *)url imageFrame:(CGRect)imageFrame userInfo:(NSDictionary *)userInfo completed:(void(^)(UIImage *image,  NSError *error, BOOL finished))completedBlock
{
    if ([url hasPrefix:@"//"]) {
        url = [@"http:" stringByAppendingString:url];
    }

    
    return (id<WXImageOperationProtocol>)[[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:url] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {

        
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        if (completedBlock) {
            completedBlock(image, error, finished);
        }
    }];
}

其实就是利用 SDWebImage 这个库实现图片下载功能。而且我还发现,如果不实现 WXImgLoaderProtocol 协议,就无法在 Weex 的代码中通过 URL 加载网络图片。也就是说 Weex 其实是依赖原生来做网络图片加载,至于为什么这么做,我只能说:我不知道。

造轮子 | 如何设计一个面向协议的 iOS 网络请求库
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }