鴻蒙OS前端開發入門指南:網路圖片_Image渲染網路圖片

目錄:
1、開啟明文傳輸
2、許可權申請
3、引入http插件
4、案例展示
5、《鴻蒙OS前端開發入門指南》文章合集

開啟明文傳輸 在config.json配置文件添加如下配置(如果不開啟可以不配置)

“deviceConfig”: {
“default”: {
“network”: {
“usesCleartext”: true
}
}
},

許可權申請 在配置文件module中添加如下

“reqPermissions”: [{
“name”:”ohos.permission.INTERNET”
}],

引入zzr老師寫的鴻蒙http插件

 implementation 'com.zzrv5.zzrhttp:ZZRHttp:1.0.1'

案例1

使用方式,

new ImageNetWork(」當前的abilitySlice「,「創件的Image組建」,”圖片地址”).start();

網路圖片類

package com.example.shangjinlieren.compontents;

import com.zzrv5.mylibrary.ZZRCallBack;
import com.zzrv5.mylibrary.ZZRHttp;
import com.zzrv5.mylibrary.ZZRResponse;
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;

public class ImageNetWork {
private final static HiLogLabel LABEL_LOG = new HiLogLabel(HiLog.LOG_APP, 0, “HmOSImageLoader”);
private AbilitySlice abilitySlice;
private Image image;
private String url;

public ImageNetWork(AbilitySlice abilitySlice, Image image, String url) {
    this.abilitySlice = abilitySlice;
    this.image = image;
    this.url = url;
}

public  void start() {
    ZZRHttp.get(url, new ZZRCallBack.CallBackString() {
        @Override
        public void onFailure(int code, String errorMessage) {
            //http訪問出錯了,此部分內容在主執行緒中工作;
            //可以更新UI等操作,請不要執行阻塞操作。
            System.out.println("errorMessage"+errorMessage);
        }
        @Override
        public String onParseResponse(ZZRResponse response) {
            //創建圖片源
            ImageSource imageSource = ImageSource.create(response.inputStream, null);
            //根據圖片源創建點陣圖
            PixelMap pixelMap = imageSource.createPixelmap(null);
            //需要非同步渲染UI
            abilitySlice.getUITaskDispatcher().asyncDispatch(new Runnable() {
                @Override
                public void run() {
                    //展示到組件上
                    System.out.println("掛載了");
                    image.setPixelMap(pixelMap);
                    pixelMap.release();

                }
            });
            return super.onParseResponse(response);
        }
        @Override
        public void onResponse(String response) {

        }
    });
}

}
作者:BLUESKYHOST
想了解更多內容,請訪問51CTO和華為合作共建的鴻蒙社區://harmonyos.51cto.com/

Tags: