5

OpenHarmony实战开发-如何使用colorPicker实现背景跟随主题颜色转换。

 2 weeks ago
source link: https://blog.51cto.com/u_16506820/10512727
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

本示例介绍使用image库以及effectKit库中的colorPicker对目标图片进行取色,将获取的颜色作为背景渐变色,通过swiper组件对图片进行轮播,

效果图预览

OpenHarmony实战开发-如何使用colorPicker实现背景跟随主题颜色转换。_HarmonyOS

使用说明

直接进入页面,对图片进行左右滑动,或者等待几秒,图片会自动轮播,图片切换后即可改变背景颜色。

  1. 在事件onAnimationStart切换动画过程中通过Image模块相关能力,获取图片颜色平均值,使用effectKit库中的ColorPicker智能取色器进行颜色取值。
const context = getContext(this);
//获取resourceManager资源管理器
const resourceMgr: resourceManager.ResourceManager = context.resourceManager;
const fileData: Uint8Array = await resourceMgr.getMediaContent(this.imgData[targetIndex]);
//获取图片的ArrayBuffer
const buffer = fileData.buffer;
//创建imageSource
const imageSource: image.ImageSource = image.createImageSource(buffer);
//创建pixelMap
const pixelMap: image.PixelMap = await imageSource.createPixelMap();

effectKit.createColorPicker(pixelMap, (err, colorPicker) => {
  //读取图像主色的颜色值,结果写入Color
  let color = colorPicker.getMainColorSync();
})

2.同时通过接口animateTo开启背景颜色渲染的属性动画。全局界面开启沉浸式状态栏。

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);
})

3.通过属性linearGradient设置背景色渲染方向以及渲染氛围。

linearGradient({
  //渐变方向
  direction: GradientDirection.Bottom,
  //数组末尾元素占比小于1时,满足重复着色的效果
  colors: [[this.bgColor, 0.0], [Color.White, 0.5]]
})

工程结构&模块类型

effectKit                                  // har类型
|---pages
|---|---MainPage.ets                       // 视图层-场景列表页面

高性能知识点

转发+关注 小编会更新更多开发相关技术及岗位发展前景提供给大家参考学习。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK