HarmonyOS 如何解决canvas设置文字对齐的方法 textAlign不起效果?

如何解决canvas设置文字对齐的方法 textAlign不起效果?

HarmonyOS
2024-12-20 16:56:39
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
fox280

参考demo:

// xxx.ets
@Entry
@Component
struct CanvasExample {
  private settings: RenderingContextSettings = new RenderingContextSettings(true)
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)

  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
      Canvas(this.context)
        .width('100%')
        .height('100%')
        .backgroundColor('#ffff00')
        .onReady(() => {
          this.context.fillStyle = '#0000ff'
          this.context.font = '18vp'
          this.context.fillStyle = Color.Black
          this.context.textAlign = 'center'
          this.context.textBaseline = 'middle'
          let str = (-10.3456).toFixed(2)
          let metrics = this.context.measureText(str)
          this.context.fillStyle = Color.Green //这里把文字显示的区域绘制出来
          this.context.fillRect(10, (this.context.height - metrics.height) / 2, metrics.width, metrics.height)
          this.context.fillStyle = Color.Black //这里把文字绘制出来
          this.context.fillText(str, 10 + (metrics.width / 2), (this.context.height) / 2)
        })
    }
    .width('100%')
    .height('100%')
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
分享
微博
QQ
微信
回复
2024-12-20 18:54:47
相关问题
HarmonyOS 拖拽起效果
955浏览 • 1回复 待解决
Tabs组件tabBar,能否设置对齐方法
1174浏览 • 1回复 待解决
有没有给canvas设置ColorFilter方法
1234浏览 • 1回复 待解决
HarmonyOS Canvas设置渐变色没有效果
821浏览 • 1回复 待解决
HarmonyOS使用canvas如何使文字垂直居中
1417浏览 • 1回复 待解决
HarmonyOS 文字标题没有垂直居中对齐
604浏览 • 1回复 待解决
HarmonyOS toast问题如何解决
1958浏览 • 1回复 待解决
HarmonyOS 2300061报错如何解决
1070浏览 • 1回复 待解决
canvas如何实现水印效果
1809浏览 • 1回复 待解决
HarmonyOS如何实现文字轮播效果
1123浏览 • 1回复 待解决
HarmonyOS canvas如何实现画线跟手效果
724浏览 • 1回复 待解决
HarmonyOS Canvas如何设置圆角
735浏览 • 1回复 待解决