鸿蒙实现背景色自适应图片颜色

源码:背景跟随图片主要颜色自适应: 鸿蒙如何设置背景自适应

本案例以轮播图组件展示该效果,朋友们可以按照这个流程思路迁移应用到其他组件

中国万岁,人民万岁,中国人民大团结万岁,中国科技大突围万岁。

准备用于演示的图片

1,获取应用上下文

2,获取资源管理器

  const context = getContext()
    const resoureMgr = context.resourceManager;

3,获取图片数据

  //获取图片数据
        const imgData = await resoureMgr.getMediaContent(this.imgDatas[index])

4,转为ArrayBuffer数组

  // ArrayBuffer 对象用来表示通用的、固定长度的原始二进制数据缓冲区。
        const buffer = imgData.buffer

5,创造一个图片源数据

const imgSourse = image.createImageSource(buffer)

6,创建像素图对象

const pixelMap = imgSourse.createPixelMapSync();

7,创造颜色选择器,使用getMainColorSync()拿到图片主要颜色

effectKit.createColorPicker(pixelMap, (err, pricker) => {
  let color = pricker.getMainColorSync()
  animateTo({
    duration: 1000,
    curve: Curve.Linear,
    iterations: 1
  }, () => {
//this.bgColor为背景色的状态变量,下面分别为设置透明度和颜色color 为获取的像素图主要色
    this.bgColor = "#" + color.alpha.toString(16) +
    color.red.toString(16) + color.green.toString(16) +
    color.blue.toString(16);
  })
})

 给组件设置渐变色效果更好

 8,突破安全区

因为鸿蒙会自带安全区设置但是我们的业务有可能需要重新设置安全区的颜色等等,如果不突破安全区会出现如下情况上方会留白

//固定写法
    const win = await window.getLastWindow(getContext())
    //设置全屏
    win.setWindowLayoutFullScreen(true)
    // 获取顶部状态栏高度
    const topArea = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM)
    //获取底部导航条高度
    const bottomArea = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR)
    //转换为鸿蒙默认的vp单位
    this.topheight = px2vp(topArea.topRect.height)
    this.bottomheight=px2vp(bottomArea.bottomRect.height)














最后给根容器设置一个上下边距
    .padding({ top: this.topheight,bottom:this.bottomheight })

最后当当当当,我最爱的绘梨衣就是这个效果了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值