一、如果图片为【http】开头的,则需要打开:
"deviceConfig": {
"default": {
"network": {
"cleartextTraffic": true
}
}
}
鸿蒙的默认是https访问模式
二、加载图片,这里以OKHttp3为例:
public static void setImages(Context context, Image imageView, String url) {
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, new ImageSource.SourceOptions());
ImageSource.DecodingOptions decodingOptions =new ImageSource.DecodingOptions();
decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
//根据图片源创建位图
PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);
//展示到组件上
context.getUITaskDispatcher().delayDispatch(new Runnable() {
@Override
public void run() {
imageView.setPixelMap(pixelMap);
//释放位图
pixelMap.release();
}
}, 0);
}catch (IOException e) {
LogUtil.iYx(" ----- " + e.getMessage());
e.printStackTrace();
}
}).start();
}
官方用例中也有一种,附上链接:https://developer.huawei.com/consumer/cn/forum/topic/0204410755673870341?fid=0101303901040230869