鸿蒙开发-字体渐变如何实现

272 阅读1分钟

在开发过程中,会遇到设计图中有渐变字体,但是又不想麻烦UI小姐姐,利用代码是否可以实现渐变文字的效果呢

根据查询官方文档发现在 @ohos.graphics.drawing (绘制模块)可以实现镂空效果

249dcf9508f096fcacffde55a36bf8f.png 由图我们看出两者相叠加就可以出现背景颜色

那么,使用层叠布局,文字在上,纯色背景在下是不是就可以实现文字镂空效果

理论成立,实践开始:

recording.gif

为了方便观察效果在最外层设置粉色的背景颜色

文字和背景色叠加就出现了文字镂空效果

那么给其设置一个渐变的背景就可以实现文字渐变

recording.gif

到了这里有了一个问题,设置渐变背景盒子的宽度和高度应该设置多少呢

查看官方文档可以发现 @ohos.measure (文本计算)可以计算文本的宽度和高度

const textSize  = MeasureText.measureTextSize({
  textContent: this.words,
  fontSize: this.fontSize
})
console.log(``, JSON.stringify(textSize))

image.png

这里的单位是px,如果要设置给背景盒子还需要进行单位换算

使用px2vp()方法实现px转vp

完整代码

import { MeasureText } from '@kit.ArkUI'
@Entry
@Component
struct Index {
  @State words: string = ''
  @State fontSize: number = 50
  @State textWidth: number = 0
  @State textHeight: number = 0
  @State x: number = -300

  aboutToAppear(){
    this.words = '鸿蒙开发'
    const textSize  = MeasureText.measureTextSize({
      textContent: this.words,
      fontSize: this.fontSize
    })
    console.log(``, JSON.stringify(textSize))
    this.textWidth= textSize.width as number
    this.textHeight= textSize.height as number
  }

  build() {
    Column(){
      Stack() {
        // 渐变背景
        Column(){}
        .width(px2vp(this.textWidth))
        .height(px2vp(this.textHeight))
        .linearGradient({
          direction: GradientDirection.Right,
          colors: [['red', 0], ['#fc0', 1]]
        })
        Stack() {
          // 在内部Stack中绘制镂空文字
          Text(this.words)
            .fontSize(this.fontSize)
            .fontWeight(FontWeight.Bolder)// 加粗
            .blendMode(BlendMode.XOR, BlendApplyType.OFFSCREEN)
            .offset({x: this.x, y: 0})
            .animation({duration:3000})
        }
        .blendMode(BlendMode.SRC_OVER, BlendApplyType.OFFSCREEN)
        .backgroundColor(Color.White)
      }
      .margin({top:50})
      Button('文字出现')
        .onClick(()=>{
          this.x = 0
        })
    }

    .width('100%')
    .height('100%')
    .backgroundColor(Color.Pink)

  }
}