【关键字】
Text / 文字渐变 / 背景色渐变
【问题描述】
.linearGradient({
direction: GradientDirection.Right,
colors: [[0xcaddf3,1.0],[0xffffff,1.0],[0xbabfd5,1.0]]
})
上述代码可以设置背景色渐变,怎么设置文字渐变色?
【解决方案】
对于Text组件来说,如果直接设置属性linearGradient它不会自动将文字颜色变成渐变色,而是会将背景色变成渐变色。
可以参考使用canvas画布CanvasRenderingContext2D的fillstyle属性支持渐变色。
示例代码如下:
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D= new CanvasRenderingContext2D(this.settings)
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.linearGradient({
direction: GradientDirection.Left, // 渐变方向
colors: [[0xf88b57, 0.0], [0xaee4a0, 0.4], [0xc4d1ec, 0.7], [0xc08dcc, 0.9]] // 数组末尾元素占比小于1时满足重复着色效果
})
Canvas(this.context)
.onReady(() =>{
//绘制填充类文本
var grad = this.context.createLinearGradient(50,0, 300,100)
grad.addColorStop(0.0, '#f88b57')
grad.addColorStop(0.4, '#aee4a0')
grad.addColorStop(0.7, '#c4d1ec')
grad.addColorStop(0.9, '#c08dcc')
this.context.fillStyle = grad
this.context.font = '147px sans-serif';
this.context.fillText("Hello World!", 45, 100);
})
}
.width('100%')
}
.height('100%')
}
}