项目源码地址
项目源码已发布到GitCode平台, 方便开发者进行下载和使用。
harmonyOSAvatar
项目效果演示
主页面效果如下:
侧边栏效果如下
1. 概述
本教程详细介绍如何在HarmonyOS应用中实现网络图片加载、图片处理以及动态提取图片主色调作为UI背景色的功能。这种技术可以让应用界面根据内容自动调整配色方案,提升用户体验和视觉效果。
2. 技术要点
本教程涵盖以下关键技术点:
- 使用
@kit.NetworkKit
进行网络图片资源加载 - 图片格式转换(ArrayBuffer到PixelMap)
- 使用
effectKit
提取图片主色调 - 动态更新UI背景色并应用渐变效果
- 使用
animateTo
实现平滑的颜色过渡动画
3. 环境准备
3.1 依赖引入
首先,需要在项目中引入以下必要的依赖模块:
import { http } from '@kit.NetworkKit';
import { promptAction } from '@kit.ArkUI';
import ResponseCode from '@ohos.net.http';
import image from '@ohos.multimedia.image';
import effectKit from '@ohos.effectKit';
这些模块分别用于:
@kit.NetworkKit
:提供网络请求功能@kit.ArkUI
:提供UI交互组件,如Toast提示@ohos.net.http
:提供HTTP响应码常量@ohos.multimedia.image
:提供图片处理功能@ohos.effectKit
:提供图像特效处理,包括颜色提取
4. 网络图片加载实现
4.1 基本流程
网络图片加载的基本流程包括:创建HTTP请求、发送请求获取图片数据、处理响应结果、错误处理。
4.2 代码实现
@State bgColor: string = '#fff000' // 初始背景色
/**
* 通过http的request方法从网络下载图片资源
*/
async getPicture() {
try {
const httpRequest = http.createHttp();
const response = await new Promise<http.HttpResponse>((resolve, reject) => {
httpRequest.request(
this.dataBg.img, // 图片URL
(error, data) => error ? reject(error) : resolve(data)
);
});
this.transcodePixelMap(response);
} catch (error) {
console.log('图片加载失败', this.dataBg.img + '')
promptAction.showToast({
message: '图片加载失败,请检查网络或URL',
duration: 2000
});
console.error("getPicture Error:", error);
}
}
4.3 关键点解析
- 使用
http.createHttp()
创建HTTP请求实例 - 使用Promise封装异步请求,便于使用async/await语法
- 完善的错误处理机制,包括控制台日志和用户友好的Toast提示
- 成功获取图片数据后,调用
transcodePixelMap
方法进行图片处理
5. 图片处理与格式转换
5.1 ArrayBuffer转PixelMap
在HarmonyOS中,网络请求返回的图片数据通常是ArrayBuffer格式,需要转换为PixelMap才能进行后续处理。
5.2 代码实现
/**
* 使用createPixelMap将ArrayBuffer类型的图片装换为PixelMap类型
* @param data:网络获取到的资源
*/
transcodePixelMap(data: http.HttpResponse) {
if (ResponseCode.ResponseCode.OK === data.responseCode) {
const imageData: ArrayBuffer = data.result as ArrayBuffer;
// 通过ArrayBuffer创建图片源实例
const imageSource: image.ImageSource = image.createImageSource(imageData);
const options: image.InitializationOptions = {
'alphaType': 0, // 透明度
'editable': false, // 是否可编辑
'pixelFormat': 3, // 像素格式
'scaleMode': 1, // 缩略值
'size': { height: 100, width: 100 }
}; // 创建图片大小
// 通过属性创建PixelMap
imageSource.createPixelMap(options).then((pixelMap: PixelMap) => {
// 提取图片主色调
effectKit.createColorPicker(pixelMap, (err, colorPicker) => {
//读取图像主色的颜色值,结果写入Color
let color = colorPicker.getMainColorSync();
// 开启背景颜色渲染的属性动画
animateTo({ duration: 500, curve: Curve.Linear, iterations: 1 }, () => {
// 将取色器选取的color示例转换为十六进制颜色代码
this.bgColor = "#" + color.alpha.toString(16) + color.red.toString(16) +
color.green.toString(16) + color.blue.toString(16);
})
})
});
}
}
5.3 关键点解析
- 使用
image.createImageSource()
从ArrayBuffer创建图片源 - 配置
InitializationOptions
设置图片属性,如尺寸、透明度等 - 调用
createPixelMap()
方法生成PixelMap对象 - 图片处理采用Promise链式调用,确保操作顺序
6. 图片主色调提取
6.1 使用effectKit提取主色调
HarmonyOS提供了强大的effectKit
模块,可以轻松提取图片的主色调。
6.2 代码实现
// 提取图片主色调
effectKit.createColorPicker(pixelMap, (err, colorPicker) => {
//读取图像主色的颜色值,结果写入Color
let color = colorPicker.getMainColorSync();
// 开启背景颜色渲染的属性动画
animateTo({ duration: 500, curve: Curve.Linear, iterations: 1 }, () => {
// 将取色器选取的color示例转换为十六进制颜色代码
this.bgColor = "#" + color.alpha.toString(16) + color.red.toString(16) +
color.green.toString(16) + color.blue.toString(16);
})
})
6.3 关键点解析
- 使用
effectKit.createColorPicker()
创建颜色提取器 - 调用
getMainColorSync()
同步获取图片主色调 - 将RGBA颜色值转换为十六进制颜色代码
- 使用
animateTo()
创建平滑的颜色过渡动画
7. 动态背景色应用
7.1 在UI中应用提取的颜色
提取的主色调可以应用到UI的各个部分,如背景色、渐变色等。
7.2 代码实现
// 在组件中应用动态背景色
Column() {
SlideBarList()
}.linearGradient({
// 渐变方向
direction: GradientDirection.Bottom,
colors: [[this.bgColor, 0.1], [Color.White, 0.5]]
})
.justifyContent(FlexAlign.Center)
7.3 关键点解析
- 使用
linearGradient
属性创建渐变背景 - 将提取的主色调
this.bgColor
作为渐变起始色 - 设置适当的透明度和渐变方向,增强视觉效果
8. 状态管理与数据监听
8.1 使用@Watch监听数据变化
为了在数据变化时自动更新UI,我们使用@Watch
装饰器监听相关状态变量。
8.2 代码实现
@Provide @Watch('handleDataBg') dataBg: DataBgClass = new DataBgClass('626d05e010ec0f00014b21f1',
'https://jushubiotech.oss-cn-beijing.aliyuncs.com/rc/facemacker/bgimg/0.jpg', '国庆节',
'和我一起使用国庆节头像吧',
'https://image.jushubiotech.com/rc/facemacker/titeImg/0.png')
// 监听处理函数
handleDataBg() {
this.getPicture()
}
8.3 关键点解析
- 使用
@Provide
装饰器提供数据给子组件 - 使用
@Watch
监听数据变化并触发回调函数 - 在回调函数中调用
getPicture()
重新加载图片并提取颜色
9. 总结
本教程详细介绍了如何在HarmonyOS应用中实现网络图片加载、处理以及动态提取主色调作为UI背景色的功能。通过这些技术,可以创建出更具视觉吸引力和个性化的用户界面,提升应用的整体用户体验。
动态背景色提取不仅适用于头像编辑器应用,还可以应用于图片浏览器、音乐播放器、新闻阅读器等各种应用场景,为用户带来更加沉浸式的体验。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。