HarmonyOS/OpenHarmony应用开发-ArkTS画布组件CanvasRenderingContext2D对象(十一)

measureText

measureText(text: string): TextMetrics

该方法返回一个文本测算的对象,通过该对象可以获取指定文本的宽度值。

HarmonyOS/OpenHarmony应用开发-ArkTS画布组件CanvasRenderingContext2D对象(十一)_第1张图片

 

示例:

  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct MeasureText {
  5.   private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6.   private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7.   build() {
  8.     Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9.       Canvas(this.context)
  10.         .width('100%')
  11.         .height('100%')
  12.         .backgroundColor('#ffff00')
  13.         .onReady(() =>{
  14.           this.context.font = '50px sans-serif'
  15.           this.context.fillText("Hello World!", 20, 100)
  16.           this.context.fillText("width:" + this.context.measureText("Hello World!").width, 20, 200)
  17.       })
  18.     }
  19.     .width('100%')
  20.     .height('100%')
  21.   }
  22. }

HarmonyOS/OpenHarmony应用开发-ArkTS画布组件CanvasRenderingContext2D对象(十一)_第2张图片

 

stroke

stroke(path?: Path2D): void

进行边框绘制操作。

参数:

参数

类型

必填

默认值

描述

path

Path2D

null

需要绘制的Path2D。

示例:

  1. // xxx.ets
  2. @Entry
  3. @Component
  4. struct Stroke {
  5.   private settings: RenderingContextSettings = new RenderingContextSettings(true)
  6.   private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  7.   build() {
  8.     Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
  9.       Canvas(this.context)
  10.         .width('100%')
  11.         .height('100%')
  12.         .backgroundColor('#ffff00')
  13.         .onReady(() =>{
  14.           this.context.moveTo(25, 25)
  15.           this.context.lineTo(25, 105)
  16.           this.context.lineTo(75, 105)
  17.           this.context.lineTo(75, 25)
  18.           this.context.strokeStyle = 'rgb(0,0,255)'
  19.           this.context.stroke()
  20.         })
  21.     }
  22.     .width('100%')
  23.     .height('100%')
  24.   }
  25. }

HarmonyOS/OpenHarmony应用开发-ArkTS画布组件CanvasRenderingContext2D对象(十一)_第3张图片

 

你可能感兴趣的:(前端,css,html)