安卓 接入Weex Base64位圖片無法顯示完美解決辦法

最近需求中需要接入Weex 老規矩 先擼一遍文檔 很順利接完 結果官網偏偏沒給加載圖片的具體方案

添加依賴

     compile 'com.taobao.android:weex_sdk:0.17.0'
     這個有多個版本 建議用新的
     compile 'com.alibaba:fastjson:1.1.46.android'
     compile 'com.android.support:recyclerview-v7:24.1.0'
     compile 'com.android.support:appcompat-v7:24.1.0'
     Weex的底層依賴這三個包 如果沒有就添加上  

到這裏基本完事 開始初始化 在Applocation中調用

        WXEnvironment.addCustomOptions("appName","TBSample");
        WXSDKEngine.initialize(this,
                new InitConfig.Builder()
                        .setImgAdapter(new ImageAdapter())
                        .build());

這裏的ImageAdapter需要自己自定義,並且繼承IWXImgLoaderAdapter 並實現其中的方法

加載圖片的關鍵就在這裏,網上一大堆重複的代碼,比如採用Picasso加載圖片,很大一部分沒什麼用處,因爲我們拿到的很可能是Base64位的圖片 當然也可以手動Base64轉Bitmap ,但是不保證每次都能成功,起碼我自己就沒成功,看代碼

public class ImageAdapter implements IWXImgLoaderAdapter {

  @Override
  public void setImage(final String url, final ImageView view,
                       WXImageQuality quality, WXImageStrategy strategy) {

    WXSDKManager.getInstance().postOnUiThread(new Runnable() {

      @Override
      public void run() {
        if (view == null || view.getLayoutParams() == null) {
          return;
        }
        if (TextUtils.isEmpty(url)) {
          view.setImageBitmap(null);
          return;
        }
        String temp = url;
        if (url.startsWith("//")) {
          temp = "http:" + url;
        }
        if (view.getLayoutParams().width <= 0 || view.getLayoutParams().height <= 0) {
          return;
        }
        Uri uri = Uri.parse(temp);

        ImageDecodeOptions decodeOptions = ImageDecodeOptions.newBuilder()
                .setBackgroundColor(Color.GREEN)
                .build();

        ImageRequest request = ImageRequestBuilder
                .newBuilderWithSource(uri)
                .setImageDecodeOptions(decodeOptions)
                .setAutoRotateEnabled(true)
                .setLocalThumbnailPreviewsEnabled(true)
                .setLowestPermittedRequestLevel(ImageRequest.RequestLevel.FULL_FETCH)
                .setProgressiveRenderingEnabled(false)
                .build();

        if (view instanceof DraweeView) {
          Log.d("FrescoImageAdapter", "load: " + url);
          ControllerListener controllerListener = new BaseControllerListener<ImageInfo>() {
            @Override
            public void onFinalImageSet(
                    String id,
                    @Nullable ImageInfo imageInfo,
                    @Nullable Animatable anim) {
              if (imageInfo == null) {
                return;
              }
              QualityInfo qualityInfo = imageInfo.getQualityInfo();
              FLog.d("Final image received! " +
                              "Size %d x %d",
                      "Quality level %d, good enough: %s, full quality: %s",
                      imageInfo.getWidth(),
                      imageInfo.getHeight(),
                      qualityInfo.getQuality(),
                      qualityInfo.isOfGoodEnoughQuality(),
                      qualityInfo.isOfFullQuality());
            }

            @Override
            public void onIntermediateImageSet(String id, @Nullable ImageInfo imageInfo) {
              FLog.d("", "Intermediate image received");
            }

            @Override
            public void onFailure(String id, Throwable throwable) {
              FLog.e(getClass(), throwable, "Error loading %s", id);
            }
          };
          DraweeController controller = Fresco.newDraweeControllerBuilder()
                  .setAutoPlayAnimations(true)
                  .setControllerListener(controllerListener)
                  .setUri(uri)
                  .setImageRequest(request)
                  .build();
          ((DraweeView) view).setController(controller);

        } else {
          ImagePipeline imagePipeline = Fresco.getImagePipeline();
          DataSource<CloseableReference<CloseableImage>>
                  dataSource = imagePipeline.fetchDecodedImage(request, new Object());
          DataSubscriber dataSubscriber =
                  new BaseDataSubscriber<CloseableReference<CloseableImage>>() {
                    @Override
                    public void onNewResultImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {

                      CloseableReference<CloseableImage> imageReference = dataSource.getResult();
                      if (imageReference != null) {
                        try {
                          // do something with the image
                          Preconditions.checkState(CloseableReference.isValid(imageReference));
                          CloseableImage closeableImage = imageReference.get();
                          if (closeableImage instanceof CloseableStaticBitmap) {
                            CloseableStaticBitmap closeableStaticBitmap = (CloseableStaticBitmap) closeableImage;
                            view.setImageBitmap(closeableStaticBitmap.getUnderlyingBitmap());
                            // boolean hasResult =  null != closeableStaticBitmap.getUnderlyingBitmap();
                          } else {
                            throw new UnsupportedOperationException("Unrecognized image class: " + closeableImage);
                          }
                        } finally {
                          imageReference.close();
                        }
                      }
                    }

                    @Override
                    public void onFailureImpl(DataSource dataSource) {
                    }
                  };

          dataSource.subscribe(dataSubscriber, UiThreadImmediateExecutorService.getInstance());
        }
      }
    }, 0);
  }
}



這裏用的 Fresco來加載圖片 Picasso默認是不支持加載Base64位的圖片的 至於其他的能不能加載可以嘗試一下,不過用此方法基本可行。需要添加上這兩個依賴

    compile 'com.facebook.fresco:fresco:0.12.0+'
    compile 'com.facebook.fresco:animated-gif:0.12.0'

新建一個類來渲染界面

public class WeexActivity extends AppCompatActivity implements IWXRenderListener{

    @BindView(R.id.WeexGroup)
    RelativeLayout WeexGroup;
    private WXSDKInstance mWXSDKInstance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weex);
        ButterKnife.bind(this);
        mWXSDKInstance = new WXSDKInstance(this);
        mWXSDKInstance.registerRenderListener(this);
        mWXSDKInstance.renderByUrl("WXSample","http://dotwe.org/raw/dist/1721a811dc70c3cc3dc25263bb36f2aa.bundle.wx",null, null, -1, -1, WXRenderStrategy.APPEND_ASYNC);
    }


    @Override
    public void onViewCreated(WXSDKInstance instance, View view) {
        WeexGroup.addView(view);
        System.out.println("----------onViewCreated"  + view+"  " + instance);
    }

    @Override
    public void onRenderSuccess(WXSDKInstance instance, int width, int height) {
        System.out.println("----------onRenderSuccess" + width+"   " + height+"  " + instance);
    }

    @Override
    public void onRefreshSuccess(WXSDKInstance instance, int width, int height) {
        System.out.println("----------onRefreshSuccess" + width+"   " + height+"  " + instance);
    }

    @Override
    public v`這裏寫代碼片`oid onException(WXSDKInstance instance, String errCode, String msg) {
        System.out.println("----------onException" + msg+"   " + errCode+"  " + instance);
    }
}
我這裏用的是加載網絡的js  當然也可以加載本地的  具體的細節官網給的很清楚,以及參數等等

xml文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/WeexGroup"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</RelativeLayout>

大概就這麼多內容 基本的加載調用就可以了 關於其他錯誤

這裏需要添加
    defaultConfig {
        ndk {
            abiFilters "x86"
            abiFilters "armeabi"
        }
        如果編譯不通過 那麼
gradle.properties中添加  android.useDeprecatedNdk=true   重新編譯即可  到此,坑就填平了。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章