weex并没有提供图片下载的能力,所以就要我们在native端来实现。所以顺便讲一下如何加载本地图片。
一、网络图片
1、创建一个继承自NSObject的类
2、pod 导入SDWebImage(使用这个库下载图片)
2、实现WXImgLoaderProtocol
3、具体实现如下
- (id<WXImageOperationProtocol>)downloadImageWithURL:(NSString *)url imageFrame:(CGRect)imageFrame userInfo:(NSDictionary *)options completed:(void (^)(UIImage *, NSError *, BOOL))completedBlock
{
if (![self isValidString:url]) {
return nil;
}
if ([url hasPrefix:@"//"]) {
url = [@"http:" stringByAppendingString:url];
}
SDWebImageManager *mgr = [SDWebImageManager sharedManager];
id op = [mgr downloadImageWithURL:[NSURL URLWithString:url]
options:SDWebImageRetryFailed
progress:nil
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
if (completedBlock) {
completedBlock(image, error, finished);
}
}];
return (id<WXImageOperationProtocol>)op;
}
- (BOOL)isValidString:(NSString *)str
{
if (str && [str isKindOfClass:[NSString class]] && [str length] > 0) {
return YES;
}
return NO;
}
其实官网都说的听清楚了,照着来基本上问题都不大。下面再说说如何实现加载本地图片
二、本地图片
在上面的基础上
实现的方式也是比较简单,网络图片是下载好图片回调给weex显示,本地是不是也可以 加载好本地的回调给weex显示,具体实现看一下代码大家瞬间就明白了。
- (id<WXImageOperationProtocol>)downloadImageWithURL:(NSString *)url imageFrame:(CGRect)imageFrame userInfo:(NSDictionary *)options completed:(void (^)(UIImage *, NSError *, BOOL))completedBlock
{
if (![self isValidString:url]) {
return nil;
}
//实现加载xcassets 本地资源文件
if ([url hasPrefix:@"assets:"]) {
UIImage *image = [UIImage imageNamed:[url substringFromIndex:7]];
completedBlock(image, nil, YES);
return (id<WXImageOperationProtocol>)[NSObject new];
}
if ([url hasPrefix:@"//"]) {
url = [@"http:" stringByAppendingString:url];
}
SDWebImageManager *mgr = [SDWebImageManager sharedManager];
id op = [mgr downloadImageWithURL:[NSURL URLWithString:url]
options:SDWebImageRetryFailed
progress:nil
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
if (completedBlock) {
completedBlock(image, error, finished);
}
}];
return (id<WXImageOperationProtocol>)op;
}
- (BOOL)isValidString:(NSString *)str
{
if (str && [str isKindOfClass:[NSString class]] && [str length] > 0) {
return YES;
}
return NO;
}
JS中只需要写好前缀就可以了。看代码
<image class="soureImageStyle" src="assets:moren2"/>
demo 下的downloadImageDemo工程 vue文件也在项目路径下。