【HarmonyOS】仿iOS线性渐变实现

【HarmonyOS】仿照IOS中可以通过输入start=(0,0),end=(1,1)获取角度到.linearGradient,从而实现左上到右下渐变

cke_477.png

 

复制代码
class Point {
  x: number = 0
  y: number = 0
}


@Entry
@Component
struct Page57 {
  @State message: string = 'Hello World';

  //输入start=(0,0),end=(1,1)实现左上到右下渐变
  private calculateGradientAngle(start: Point, end: Point): number {
    // 计算两点之间的向量
    const dx = end.x - start.x;
    const dy = end.y - start.y;

    // 使用 Math.atan2(dy, dx) 计算角度
    // Math.atan2 返回的是弧度值,需要转换为角度
    const radian = Math.atan2(dy, dx);
    const degree = radian * (180 / Math.PI);

    console.info(`degree:${degree}`)
    // 根据实际情况调整角度
    // 从左上角到右下角的角度通常是 45 度
    return (90 + degree) % 360;
  }

  build() {
    Column() {
      Text('背景渐变')
      Row() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
        //.blendMode(BlendMode.DST_IN, BlendApplyType.OFFSCREEN)
      }.linearGradient({
        angle: this.calculateGradientAngle({ x: 0, y: 0 }, { x: 1, y: 1 }),
        colors: [[0xff0000, 0.0], [0x0000ff, 1.0]]
      }) //.blendMode(BlendMode.SRC_OVER, BlendApplyType.OFFSCREEN)
      Text('文字渐变')
      Row() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .blendMode(BlendMode.DST_IN, BlendApplyType.OFFSCREEN)
      }.linearGradient({
        angle: this.calculateGradientAngle({ x: 0, y: 0 }, { x: 1, y: 1 }),
        colors: [[0xff0000, 0.0], [0x0000ff, 1.0]]
      }).blendMode(BlendMode.SRC_OVER, BlendApplyType.OFFSCREEN)
    }
    .width('100%')
    .height('100%')
  }
}
复制代码

 

posted @   zhongcx  阅读(20)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示