Weex组件:<image>

官方手册

  • <image> 组件用于渲染图片,并且它不能包含任何子组件。可以用<img> 作简写。

  • 需要注意的是,需要明确指定 widthheight,否则图片无法显示。

  • <image> 组件不支持任何子组件,

特性

  • src {string}:定义图片链接,目前图片暂不支持本地图片。
  • resize {string}:可以控制图片的拉伸状态,值行为和 W3C 标准一致。
    可选值为:
    stretch:默认值,指定图片按照容器拉伸,有可能使图片产生形变。
    cover:指定图片可以被调整到容器,以使图片完全覆盖背景区域,图片有可能被剪裁。
    contain:指定可以不用考虑容器的大小,把图像扩展至最大尺寸,以使其宽度和高度完全适应内容区域。
  • placeholder: <string> 当源图片下载中时显示一张占位图。

事件

  • load: 当图片加载完成时触发。

示例

<template>
  <scroller class="wrapper" >
    <div class="page-head" >
      <image class="title-bg" resize="cover" src="https://img.alicdn.com/tps/TB1dX5NOFXXXXc6XFXXXXXXXXXX-750-202.png"></image>
      <div class="title-box">
        <text class="title">Alan Mathison Turing</text>
      </div>
    </div>
    <div class="article">
      <text class="paragraph">Alan Mathison Turing ( 23 June 1912 – 7 June 1954) was an English computer scientist, mathematician, logician, cryptanalyst and theoretical biologist. He was highly influential in the development of theoretical computer science, providing a formalisation of the concepts of algorithm and computation with the Turing machine, which can be considered a model of a general purpose computer.Turing is widely considered to be the father of theoretical computer science and artificial intelligence.</text>
      <text class="paragraph">During the Second World War, Turing worked for the Government Code and Cypher School (GC&CS) at Bletchley Park, Britain's codebreaking centre. For a time he led Hut 8, the section responsible for German naval cryptanalysis. He devised a number of techniques for speeding the breaking of German ciphers, including improvements to the pre-war Polish bombe method, an electromechanical machine that could find settings for the Enigma machine. Turing played a pivotal role in cracking intercepted coded messages that enabled the Allies to defeat the Nazis in many crucial engagements, including the Battle of the Atlantic; it has been estimated that this work shortened the war in Europe by more than two years and saved over fourteen million lives.</text>
      <text class="paragraph">After the war, he worked at the National Physical Laboratory, where he designed the ACE, among the first designs for a stored-program computer. In 1948 Turing joined Max Newman's Computing Machine Laboratory at the Victoria University of Manchester, where he helped develop the Manchester computers and became interested in mathematical biology. He wrote a paper on the chemical basis of morphogenesis, and predicted oscillating chemical reactions such as the Belousov–Zhabotinsky reaction, first observed in the 1960s.</text>
      <text class="paragraph">Turing was prosecuted in 1952 for homosexual acts, when by the Labouchere Amendment, "gross indecency" was still criminal in the UK. He accepted chemical castration treatment, with DES, as an alternative to prison. Turing died in 1954, 16 days before his 42nd birthday, from cyanide poisoning. An inquest determined his death as suicide, but it has been noted that the known evidence is also consistent with accidental poisoning. In 2009, following an Internet campaign, British Prime Minister Gordon Brown made an official public apology on behalf of the British government for "the appalling way he was treated." Queen Elizabeth II granted him a posthumous pardon in 2013.</text>
    </div>
  </scroller>
</template>
<style>
  .page-head {
    width: 750px;
    height: 200px;
  }
  .title-bg {
    width: 750px;
    height: 200px;
  }
  .title-box {
    width: 750px;
    height: 200px;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
  }
  .title {
    color: #ffffff;
    font-size: 32px;
    font-weight: bold;
  }
  .article {
    padding: 20px;
  }
  .paragraph{
    margin-bottom: 15px;
  }
</style>

SDK 源码

  • 组件类:WXImageComponent
[self registerComponent:@"image" withClass:NSClassFromString(@"WXImageComponent") withProperties:nil];
  • 用UIImageView来实现
@interface WXImageView : UIImageView

@end
- (UIView *)loadView
{
    return [[WXImageView alloc] init];
}
- (void)viewDidLoad
{
    UIImageView *imageView = (UIImageView *)self.view;
    imageView.contentMode = _resizeMode;
    imageView.userInteractionEnabled = YES;
    imageView.clipsToBounds = YES;
    imageView.exclusiveTouch = YES;
    
    [self updateImage]; 
}
  • 关于图片图片模式,由resize参数传入,转化为UIViewContentMode进行设置
if (attributes[@"resize"]) {
    _resizeMode = [WXConvert UIViewContentMode:attributes[@"resize"]];
    self.view.contentMode = _resizeMode;
}
+ (UIViewContentMode)UIViewContentMode:(id)value
{
    if([value isKindOfClass:[NSString class]]){
        NSString *string = (NSString *)value;
        if ([string isEqualToString:@"cover"])
            return UIViewContentModeScaleAspectFill;
        else if ([string isEqualToString:@"contain"])
            return UIViewContentModeScaleAspectFit;
        else if ([string isEqualToString:@"stretch"])
            return UIViewContentModeScaleToFill;
    }
    return UIViewContentModeScaleToFill;
}
  • placeHoldersrc参数应该都是url,两者在实现上差不多,placeholder也是兼容的。
@property (nonatomic, strong) NSString *imageSrc;
@property (nonatomic, strong) NSString *placeholdSrc;
@property (nonatomic, strong) id<WXImageOperationProtocol> imageOperation;
@property (nonatomic, strong) id<WXImageOperationProtocol> placeholderOperation;
if (attributes[@"src"]) {
    _imageSrc = [[WXConvert NSString:attributes[@"src"]] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
if (attributes[@"placeHolder"] || attributes[@"placeholder"]) {
    _placeholdSrc = [[WXConvert NSString:attributes[@"placeHolder"]?attributes[@"placeHolder"]:attributes[@"placeholder"]]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
  • 取消下载:虽然cancel的方法可能没实现,不过操作会被设置为nil,下载进程会被强制取消
- (void)cancelImage
{
    [_imageOperation cancel];
    _imageOperation = nil;
    [_placeholderOperation cancel];
    _placeholderOperation = nil;
}
  • imageSharpimageQuality可以传入,是给下载协议的实现函数用的。目前一般的实现函数都不会去用,所以暂时这两个参数不用管
NSDictionary *userInfo = @{@"imageQuality":@(weakSelf.imageQuality), @"imageSharp":@(weakSelf.imageSharp)};

dispatch_async(dispatch_get_main_queue(), ^{
    weakSelf.imageOperation = [[weakSelf imageLoader] downloadImageWithURL:imageSrc imageFrame:weakSelf.calculatedFrame userInfo:userInfo completed:^(UIImage *image, NSError *error, BOOL finished) {
        dispatch_async(dispatch_get_main_queue(), ^{
            __strong typeof(self) strongSelf = weakSelf;
            
            if (weakSelf.imageLoadEvent) {
                [strongSelf fireEvent:@"load" params:@{ @"success": error? @"false" : @"true"}];
            }
            if (error) {
                downloadFailed(imageSrc, error);
                return ;
            }
            
            if (![imageSrc isEqualToString:strongSelf.imageSrc]) {
                return ;
            }
            
            if ([strongSelf isViewLoaded]) {
                ((UIImageView *)strongSelf.view).image = image;
            }
        });
    }];
});

不足之处

既然可以自定义组件,不如参考他的写法,写一个自定义的image组件,可能更好用一点

  • 下载函数通过一个协议去实现,绕了一大圈,没什么必要;当然从框架层面提高扩展性还是可以的。自定义的组件就没有必要了。
  • 下载过程放在了一个全局的串行队列之中,中间又通过GCD套了好几层的主线程。真正的下载过程,实现者一般是会另外开并行队列去做得,这里的串行队列只是去分发下载任务。所以这种做法纯粹将简单任务复杂化,有点啰嗦。比如我们用SDWebImage来实现下载过程,下面是模拟的代码
#import "ViewController.h"

static dispatch_queue_t WXImageUpdateQueue;
static NSOperationQueue *operationQueue;

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    WXImageUpdateQueue = dispatch_queue_create("com.taobao.weex.ImageUpdateQueue", DISPATCH_QUEUE_SERIAL);
    operationQueue = [[NSOperationQueue alloc] init];
    operationQueue.maxConcurrentOperationCount = 3;
    
    for (NSInteger i = 0; i < 5; i++) {
        [self updateImage:(i + 1)];
    }
}

- (void)updateImage:(NSInteger)index {
    dispatch_async(WXImageUpdateQueue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [operationQueue addOperationWithBlock:^{
                NSTimeInterval ti = 0;
                if ((1 == index) || (3 == index)) {
                    ti = 1.0;
                } else if ((2 == index) || (4 == index)) {
                    ti = 0.5;
                } else {
                    ti = 0.2;
                }
                [NSThread sleepForTimeInterval:ti];
                NSLog(@"image %ld finished", (long)index);
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"image %ld displayed", (long)index);
                });
            }];
        });
    });
}

@end
  • placeHolder也要远程下载,这个有点无语,这个除了增加网络负担,还有什么价值?
  • 实现一个本地图片加载不是比网络去图片更简单吗?为什么不实现?不理解这样做的原因。所以,还是自己写一个图片组件比较好,框架提供的,真的不好用。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,837评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,551评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,417评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,448评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,524评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,554评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,569评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,316评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,766评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,077评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,240评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,912评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,560评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,176评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,425评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,114评论 2 366
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,114评论 2 352

推荐阅读更多精彩内容

  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,387评论 0 17
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,988评论 25 707
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,086评论 4 62
  • 二、国家重点学科的目录: 国家重点学科一级学科:力学、机械工程、仪器科学与技术、材料科学与工程、动力工程及工程热物...
    DieterFront阅读 270评论 0 0
  • 情商=智商*情感训练 智商高的人并不一定情商就高。如果一个人把所有的精力用在数学领域,不顾及人际交往研究,那么未来...
    刘珠阅读 165评论 0 3