Image如何加载网络图片逻辑

发布于 2020-10-19 16:33
浏览
3收藏

因为是新系统,各种功能性更强的“轮子”都没出现,一个简单的加载网络图片实现起来都很麻烦,因为对类库的不熟悉,所以我们效率也会很低,所以分享一些组件的使用技巧,话不多说上代码!

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();
    }
}

对了,用了OKhttp框架,用习惯了,别告诉我不会导入框架

已于2020-10-19 16:54:04修改
6
收藏 3
回复
举报
回复
添加资源
添加资源将有机会获得更多曝光,你也可以直接关联已上传资源 去关联
    相关推荐