Image如何加载网络图片逻辑
Tiechui.Wang 2020-10-20 10:00:00 发布2948 浏览 15 点赞 21 收藏
HmOSImageLoader.with(this).load(urlString).into(image);
如何封装看代码
import io.reactivex.annotations.Nullable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.Image;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import java.io.InputStream;
public class HmOSImageLoader {
private final static HiLogLabel LABEL_LOG = new HiLogLabel(HiLog.LOG_APP, 0, "HmOSImageLoader");
Image image;
String url;
int defImage;
AbilitySlice abilitySlice;
private HmOSImageLoader(AbilitySlice abilitySlice) {
this.abilitySlice = abilitySlice;
}
public static HmOSImageLoader with(AbilitySlice abilitySlice) {
return new HmOSImageLoader(abilitySlice);
}
public HmOSImageLoader load(@Nullable String url) {
this.url = url;
return this;
}
public HmOSImageLoader def(@Nullable int defImage) {
this.defImage = defImage;
return this;
}
public void into(@Nullable Image image) {
this.image = image;
start();
}
private void start() {
if (defImage != 0)
image.setPixelMap(defImage);
Request request = new Request.Builder().url(url).get().build();
new Thread(() -> {
OkHttpClient okHttpClient = new OkHttpClient();
try {
//异步网络请求
Response execute = okHttpClient.newCall(request).execute();
//获取流
InputStream inputStream = execute.body().byteStream();
//利用鸿蒙api将流解码为图片源
ImageSource imageSource = ImageSource.create(inputStream, null);
//根据图片源创建位图
PixelMap pixelMap = imageSource.createPixelmap(null);
//展示到组件上
image.setPixelMap(pixelMap);
// abilitySlice.getUITaskDispatcher().asyncDispatch(() -> );
//释放位图
pixelMap.release();
} catch (IOException e) {
HiLog.error(LABEL_LOG, " ----- " + e.getMessage());
e.printStackTrace();
}
}).start();
}
}©本站发布的所有内容,包括但不限于文字、图片、音频、视频、图表、标志、标识、广告、商标、商号、域名、软件、程序等,除特别标明外,均来源于网络或用户投稿,版权归原作者或原出处所有。我们致力于保护原作者版权,若涉及版权问题,请及时联系我们进行处理。
分类
其它
标签
鸿蒙
暂无评论数据
发布
相关推荐
【开发者实战录】鸿蒙全链路赋能:看成语教育APP如何实现体验飙升与质量攻坚?
鸿蒙小助手
800
0华为鸿蒙新功能曝光:锁屏卡片如何悄悄改变你的注意力习惯
1879
0鸿蒙图片选择与裁剪实战:从相册选择到智能裁剪的完整方案
周正
2807
0华为鸿蒙亮出“组合拳”:特征卡片如何改写操作系统竞争规则
代码之外
2892
0鸿蒙进度条组件开发:从Progress到自定义加载动画
周正
2745
0
Tiechui.Wang
我还没有写个人简介......
1091
帖子
0
提问
893
粉丝
最新发布
华为应用市场增长优化师火热认证中
2025-03-10 10:16:02 发布华为应用市场斩获Pocket Gamer2023年移动游戏奖,全球第三大移动应用生态获行业认可
2024-04-27 11:06:07 发布热门推荐