Android 发展到现在不仅提供了很多 API,还提供了很多第三方库。这降低了我们开发者的开发难度,提升了开发效率,让应用开发更加的简单高效。众所周知,HarmonyOS 除了提供 16000 多个 API 外也是支持组件库的调用的,那么鸿蒙应用开发是如何与第三方库衔接的呢?
加载一张图片是每个应用所需的功能,在 Android 平台提供的有 Glide、ImageLoader、Picasso,其中 Glide 最被开发者熟知,所以我就以 Glide 作为例子验证在 HaronyOS 开发中如何使用图片加载库。
以后要引入我厂即构 ZEGO Express SDK 鸿蒙版本的时候可以根据以下的依赖方式,开发过程中需要图片的加载,也可以借鉴以下的图片加载过程。
组件库(Glide)的依赖方式
HarmonyOS 应用开发提供了三种常用的组件库引入方式,以下的三种依赖方式都是在 build.grade 中操作。
-
Maven 仓的依赖方式
以下验证过程的图片加载库 Glide 采用的就是这种方式。
步骤一:
allprojects {repositories {maven {url 'https://repo.huaweicloud.com/repository/maven/' } jcenter() mavenCentral() }}
步骤二:
dependencies {implementation fileTree(dir: 'libs', include: ['*.jar', '*.har']) implementation 'io.openharmony.tpc.thirdlib:glide:1.1.2'}
2. Module 的依赖方式
dependencies {implementation fileTree(dir: 'libs', include: ['*.jar', '*.har']) implementation project(path: ':glidelibrary')}
如果在setting.gradle 没有对该 glidelibrary 的配置,就要手动添加,如下。
include ':entry', ':glidelibrary'
3. Har 包的依赖方式
dependencies {implementation fileTree(dir: 'libs', include: ['*.jar', '*.har'])}
组件库(Glide)的使用
1. 配置
在开发前需要在 config.json 中做好配置的工作。允许 HTTP 的请求:
"deviceConfig": {"default": {"network": {"cleartextTraffic": true } }}
网络权限的设置:
"module": {"reqPermissions": [ {"name": "ohos.permission.INTERNET" } ]}
2. 加载图片
图片的来源可以是网络的图片、也可以是项目文件的图片。两种方式的加载方式如下,加载的图片来源于网络 load() 的选择 imagePath,本地图片就选择 imageResourceId。
调用方式:
Image image = (Image)findComponentById(ResourceTable.Id_img);//Load Image from Internet(图片来源于 即构官网的网络图)String imagePath = "https://www.zego.im/_nuxt/img/53992d2.png";//Load Image from Resource Folder(本地图片)int imageResourceId = ResourceTable.Media_zego_img;Glide.with(this) .load(imagePath) .diskCacheStrategy(DiskCacheStrategy.NONE) .skipMemoryCache(true) .into(image);
运行结果显示:
-
加载GIF动图
加载的GIF 图可以是网络图片,也可以说本地图片。调用方式:
DraweeView draweeView = (DraweeView) findComponentById(ResourceTable.Id_draweeView);String imagePath = "load gif from network";int imageResourceId = "load gif from native";Glide.with(this) .asGif() .load(imageResourceId) .into(draweeView);
HarmonyOS 的Image 不支持gif 的加载,因为Image和Element是独立的,不能使用Element重绘。所以 Glide 要使用 gif 的能力就要使用 DraweeView 。
<com.bumptech.glide.load.resource.gif.drawableability.DraweeViewohos:id="$+id:draweeView"ohos:height="180vp"ohos:width="180vp"ohos:layout_alignment="center"/>
因为加载 gif 的过程,对系统的性能消耗是非常大的,所以在使用完的时候要及时释放资源,防止内存泄漏。
@Overrideprotected void onBackground() {super.onBackground(); draweeView.stopGif();}
4. 加载圆角图片
加载圆角图片,把圆角 raduis 传进来,就可以绘制圆角度。
调用方式:
Image image = (Image) findComponentById(ResourceTable.Id_img);RequestOptions myOptions = new RequestOptions().transform(new GlideRoundTransform(getContext(), 30));Glide.with(this) .load(ResourceTable.Media_zego_img_round) .diskCacheStrategy(DiskCacheStrategy.NONE) .skipMemoryCache(true) .fitCenter() .apply(myOptions) .into(image);
总结
通过对 Glide 的引入过程与实现过程,跟Android 第三方库引入与图片加载没有很大的区别。
举一反三,我们可以很轻松的引入其他的组件库,也可以通过 Glide 实现其他的图片加载效果。同时一起期待我厂 即构 ZEGO Express SDK 的鸿蒙版本吧。