【HarmonyOS】鸿蒙仿iOS线性渐变实现

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

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%')
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值