图片适配器
Weex使用Image控件加载图片,但是并不能直接显示出来图片,主要还是要Native端实现图片加载,本人使用Picasso加载图片
首先在build.gradle中添加 compile 'com.squareup.picasso:picasso:2.5.2'
其次创建
ImageAdapter类,
实现IWXImgLoaderAdapter接口,在setImage方法中实现图片加载逻辑
public class ImageAdapter implements IWXImgLoaderAdapter { public ImageAdapter() { } @Override public void setImage(final String url, final ImageView view, WXImageQuality quality, final WXImageStrategy strategy) { }在本类中,可以加载本地图片和网络图片:
本人在传递相机拍照或者选择图库的图片地址给Weex时,先在图片路径前面增加一个标记头,便于区分是本地图片还是网络图片
@Override
public void setImage(final String url, final ImageView view,
WXImageQuality quality, final 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;
}
int width = view.getLayoutParams().width;
int height = view.getLayoutParams().height;
if (width <= 0 || height <= 0) {
return;
}
//去除本地文件的标记头
if (url.startsWith(Constants.mCardImgHead)) {
String urls[] = url.split("//");
if (urls.length > 1) {
temp = urls[1];
}
}
if (!TextUtils.isEmpty(strategy.placeHolder)) {
Picasso.Builder builder = new Picasso.Builder(WXEnvironment.getApplication());
Picasso picasso = builder.build();
picasso.load(Uri.parse(strategy.placeHolder)).into(view);
view.setTag(strategy.placeHolder.hashCode(), picasso);
}
Callback callback = new Callback() {
@Override
public void onSuccess() {
if (strategy.getImageListener() != null) {
strategy.getImageListener().onImageFinish(url, view, true, null);
}
if (!TextUtils.isEmpty(strategy.placeHolder)) {
((Picasso) view.getTag(strategy.placeHolder.hashCode())).cancelRequest(view);
}
}
@Override
public void onError() {
if (strategy.getImageListener() != null) {
strategy.getImageListener().onImageFinish(url, view, false, null);
}
}
};
//加载本地图片
if (url.startsWith(Constants.mZipFileHead)) {
//Picasso 加载本地图片时,必须加载"file://"文件头,不能加载不出图片
temp = URLDecoder.decode("file://" + temp);Picasso.with(WXEnvironment.getApplication()) .load(temp) .resize(width, height) .transform(new BlurTransformation(strategy.blurRadius)) .into(view, callback); } else { //加载网络图片 Picasso.with(WXEnvironment.getApplication()) .load(temp) .transform(new BlurTransformation(strategy.blurRadius)) .into(view, callback); } } }, 0); }
本地写好图片适配器后,则要告诉Weex用我写好的图片适配器
//向Weex注册图片适配器
WXSDKEngine.initialize(application, new InitConfig.Builder() .setImgAdapter(new ImageAdapter()) .build());之后就可以加载出图片啦
下一篇:加载文字库