画布绘制文字,垂直居中

需要绘制文字的时候能够垂直居中。

HarmonyOS
2024-09-23 12:08:35
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
zbw_apple

参考官网api:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-canvasrenderingcontext2d-V5

示例如下:

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)  
  })
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
分享
微博
QQ
微信
回复
2024-09-23 17:55:23
相关问题
HarmonyOS 文字标题没有垂直居中对齐
635浏览 • 1回复 待解决
HarmonyOS使用canvas如何使文字垂直居中
1422浏览 • 1回复 待解决
画布绘制图片如何实现?
861浏览 • 1回复 待解决
HarmonyOS 文字行高设定后文字居中
1025浏览 • 1回复 待解决
Text文本不垂直居中,该怎么处理呢?
4903浏览 • 1回复 待解决
HarmonyOS 弹窗文字居中
424浏览 • 1回复 待解决
HarmonyOS 文字在Row中不居中
732浏览 • 1回复 待解决
HarmonyOS 画布问题咨询
1149浏览 • 1回复 待解决