关于Harmony OS 鸿蒙加载网络图片问题分享

一、如果图片为【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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容