Weex Gif 动画加载

  • 使用 FrescoImageAdapter 覆盖原有 ImageAdapter
  • 修改 FrescoImageAdapter,使其正常调用 onload 事件

覆盖原有 ImageAdapter

App 启动的时候,使用 Fresco 代替 Picasso,并注册为 image 组件,覆盖原有组件。使用FrescoImageAdapter 后,就能支持 Gif 图片和动画了。

App.java

// FrescoImageAdapter代码 https://github.com/apache/incubator-weex/blob/master/android/commons/src/main/java/com/alibaba/weex/commons/adapter/FrescoImageAdapter.java
WXSDKEngine.registerComponent("image", FrescoImageComponent.class);

修改 FrescoImageAdapter

修改为 FrescoImageAdapter 后,发现图片的 onload 事件不能正常触发,经调试发现是没有正常触发 onImageFinish 导致的,调用onImageFinish 后,发现,无法正常获取宽高。所以,修改commons 代码:

FrescoImageAdapter.java

FrescoImageView fImageView = (FrescoImageView) view;
fImageView.setNaturalHeight(imageInfo.getHeight());
fImageView.setNaturalWidth(imageInfo.getWidth());

// 获取标签的 onload 监听事件,如果没有监听onload 事件,就不用触发了
if(strategy.getImageListener() != null) {
    strategy.getImageListener().onImageFinish(url, view, true, null);
}

FrescoImageView.java

// 需要实现 WXIMage.Measurable 接口
public class FrescoImageView extends SimpleDraweeView implements WXGestureObservable, WXImage.Measurable {

  private int naturalWidth;
  private int naturalHeight;

  public FrescoImageView(Context context) {
    super(context);
  }

  public FrescoImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public FrescoImageView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  public FrescoImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
  }

  private WXGesture wxGesture;

  @Override
  public void registerGestureListener(WXGesture wxGesture) {
    this.wxGesture = wxGesture;
  }

  @Override
  public boolean onTouchEvent(MotionEvent event) {
    boolean result = super.onTouchEvent(event);
    if (wxGesture != null) {
      result |= wxGesture.onTouch(this, event);
    }
    return result;
  }

  /* 覆盖 getNaturalWidth, getNaturalHeight 接口 */
  @Override
  public int getNaturalWidth() {
    return naturalWidth;
  }

  /* 添加 setNaturalWidth, setNaturalHeight 接口以设置当前 view 的宽高 */
  public void setNaturalWidth(int width) {
    this.naturalWidth = width;
  }

  @Override
  public int getNaturalHeight() {
    return naturalHeight;
  }

  public void setNaturalHeight(int height) {
    this.naturalHeight = height;
  }
}

其他小记

引入 SDK 源码后,发现 com.vanniktech:gradle-android-junit-jacoco-plugin 在xx 路径下找不到。这是因为本地确实没有这个包,而且,我们也没有指定去哪儿下载造成的,所以,在 SDKbuild.gradle 中,添加 mavenjcenter 仓库,使得它能正常下载。

// SDK/build.gradle
buildscript {
    repositories {
        maven {
            url 'http://maven.aliyun.com/nexus/content/groups/public/'
        }
        jcenter()
    }
    dependencies {
        classpath 'com.vanniktech:gradle-android-junit-jacoco-plugin:0.5.0'
    }
}