【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%') } }
浙公网安备 33010602011771号