【HarmonyOS NEXT】Text怎么设置文本渐变

 【关键字】

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值