目录

如何实现文本颜色渐变

问题现象

如何实现文本颜色从句首到句尾的渐变,且不被换行打断?

背景知识

解决方案

实现文本颜色渐变的方式及其适用场景内容如下:

实现场景

实现方式

适用场景

文本渐变

linearGradient+blendMode裁切背景。

API20前。

文本渐变

shaderStyle设置线性渐变参数。

更简洁,仅支持API20+。

文本渐变流光效果

linearGradient+blendMode裁切背景+流光动画。

需流光效果的场景。

常见FAQ

Q:如何使用linearGradient实现颜色在透明度上的渐变效果?

A:使用rgba格式的颜色来设置透明渐变的效果。

@Entry
@Component
struct FAQ_1 {
  build() {
    Column() {
    }
    .height('10%')
    .width('100%')
    .linearGradient(
      {
        angle: 180,
        colors: [['rgba(128,128,128,0.5)', 0.1], ['rgba(128,128,128,0.3)', 0.6], ['rgba(128,128,128,0.0)', 1]]
      })
  }
}

Q:设置linearGradient后,再设置backgroundColor,为何无效?

A:颜色渐变属于组件内容,绘制在背景上方,背景颜色是被覆盖了。设置了linearGradient渐变色,需要修改背景色为纯色,可以设置linearGradient的options的值为undefined,恢复为无线性渐变的效果。

import { FrameNode, NodeController } from '@kit.ArkUI';

class MyNodeController extends NodeController {
  makeNode(uiContext: UIContext): FrameNode | null {
    let box = new FrameNode(uiContext);
    box.commonAttribute.width(100).height(100).backgroundColor('#d1d3d5');
    let isBackgroundColor = false;
    box.commonAttribute.onClick(() => {
      isBackgroundColor = !isBackgroundColor;
      if (isBackgroundColor) {
        box.commonAttribute.backgroundColor('#d1d3d5');
        box.commonAttribute.linearGradient(undefined);
      } else {
        box.commonAttribute.linearGradient({ angle: 90, colors: [['#FF0253EB', 0], ['#FF26ECFF', 1]] });
      }
    });
    return box;
  }
}

@Entry
@Component
struct FrameNodeTypeTest {
  private myNodeController: MyNodeController = new MyNodeController();

  build() {
    Row() {
      NodeContainer(this.myNodeController);
    }
  }
}