这是需求 昨天想了老多方法 一开始以为加上线性渐变这个属性就好了
@Entry
@Component
struct TextTest {@State message: string = '中华人民共和国万岁';build() {RelativeContainer() {Text(this.message).id('TextTestHelloWorld').fontSize(33).fontWeight(FontWeight.Bold).alignRules({center: { anchor: '__container__', align: VerticalAlign.Center },middle: { anchor: '__container__', align: HorizontalAlign.Center }}).linearGradient({angle: 135,colors: [['#FD3F8F', 0], ['#FF773C', 1]]})}.height('100%').width('100%')}
}
结果
是文字背景是渐变色,但是文字还是没有变
方法一 :使用画布组件Canvas,用于自定义绘制图形。
@Entry
@Component
struct TextTest {@State message: string = '中华人民共和国万岁';private settings: RenderingContextSettings = new RenderingContextSettings(true)private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)build() {RelativeContainer() {Canvas(this.context).width(200).height(100).onReady(()=>{this.context.globalCompositeOperation = "source-in"this.context.font = "50px"let gradient = this.context.createLinearGradient(0, 0, 200, 0);gradient.addColorStop(0, 'red');gradient.addColorStop(0.5, 'green');gradient.addColorStop(0.8, 'blue');this.context.fillStyle = gradient;this.context.fillRect(0,0,200,100);this.context.fillText(this.message, 10, 40);})}.height('100%').width('100%')}
}
方法二:使用Test span属性拼接 (没有渐变的效果)
@Entry
@Component
struct TextTest {@State message: string = '中华人民共和国万岁';build() {RelativeContainer() {Text() {Span('中华人民').fontColor('#FF773C')Span('共和国').fontColor('#FD3F8F')Span('万岁').fontColor('#FF773C')}.id('TextTestHelloWorld').fontSize(33).fontWeight(FontWeight.Bold).alignRules({center: { anchor: '__container__', align: VerticalAlign.Center },middle: { anchor: '__container__', align: HorizontalAlign.Center }})// .linearGradient({// angle: 135,// colors: [['#FD3F8F', 0], ['#FF773C', 1]]// })}.height('100%').width('100%')}
}
方法三:使用blendMode 将当前控件的内容(包含子节点内容)与下方画布(可能为离屏画布)已有内容进行混合。
@Entry
@Component
struct TextTest {@State message: string = '中华人民共和国万岁';build() {RelativeContainer() {Column() {Text(this.message).id('TextTestHelloWorld').fontSize(33).fontWeight(FontWeight.Bold).blendMode(BlendMode.DST_IN, BlendApplyType.OFFSCREEN)}.linearGradient({angle: 135,colors: [['#FD3F8F', 0], ['#FF773C', 1]]}).blendMode(BlendMode.SRC_OVER, BlendApplyType.OFFSCREEN).alignRules({center: { anchor: '__container__', align: VerticalAlign.Center },middle: { anchor: '__container__', align: HorizontalAlign.Center }})}.height('100%').width('100%')}
}