【HarmonyOS 】【JAVA UI】HarmonyOS 加载网络图片
主要作用
加载网络图片功用于界面显示
参考资料
权限开发指导
线程管理
图像开发概述
代码实现
config.json配置
config.json代码如下
"reqPermissions": [ {"name": "ohos.permission.INTERNET"} ],
xml代码实现
java代码实现
package com.harmony.alliance.mydemo.slice;import com.harmony.alliance.mydemo.ResourceTable;import ohos.aafwk.ability.AbilitySlice;import ohos.aafwk.content.Intent;import ohos.agp.components.Component;import ohos.agp.components.ComponentProvider;import ohos.agp.components.Image;import ohos.media.image.ImageSource;import ohos.media.image.PixelMap;import ohos.media.image.common.PixelFormat;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLConnection;public class myImageAbilitySlice extends AbilitySlice { private Image myImage; @Override protected void onStart(Intent intent) { super.onStart(intent); setUIContent(ResourceTable.Layout_my_image); myImage=findComponentById(ResourceTable.Id_myImage); findComponentById(ResourceTable.Id_LoadImage).setClickedListener(new Component.ClickedListener() { @Override public void onClick(Component component) { new Thread(){ @Override public void run() { super.run(); LoadImageData(); } }.start(); } }); } public void LoadImageData(){ String urlImage = "https://www.harmonyos.com/resource/image/community/20201009-164134eSpace.jpg"; HttpURLConnection connection = null; try { URL url = new URL(urlImage); URLConnection urlConnection = url.openConnection(); if (urlConnection instanceof HttpURLConnection) { connection = (HttpURLConnection) urlConnection; } if (connection != null) { connection.connect(); // 之后可进行url的其他操作 // 得到服务器返回过来的流对象 InputStream inputStream = urlConnection.getInputStream(); ImageSource imageSource = ImageSource.create(inputStream, new ImageSource.SourceOptions()); ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions(); decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888; // 普通解码叠加旋转、缩放、裁剪 PixelMap pixelMap = imageSource.createPixelmap(decodingOptions); // 普通解码 getUITaskDispatcher().syncDispatch(() -> { myImage.setPixelMap(pixelMap); pixelMap.release(); }); } } catch (Exception e) { e.printStackTrace(); } }}
运行效果
欲了解更多更全技术文章,欢迎访问https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh