画布绘制文字,垂直居中?

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

阅读 574
1 个回答

参考官网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) 
  })
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进