measureText
measureText(text: string): TextMetrics
该方法返回一个文本测算的对象,通过该对象可以获取指定文本的宽度值。
示例:
- // xxx.ets
- @Entry
- @Component
- struct MeasureText {
- 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.font = '50px sans-serif'
- this.context.fillText("Hello World!", 20, 100)
- this.context.fillText("width:" + this.context.measureText("Hello World!").width, 20, 200)
- })
- }
- .width('100%')
- .height('100%')
- }
- }
stroke
进行边框绘制操作。
参数:
参数 | 类型 | 必填 | 默认值 | 描述 |
path | 否 | null | 需要绘制的Path2D。 |
示例:
- // xxx.ets
- @Entry
- @Component
- struct Stroke {
- 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.moveTo(25, 25)
- this.context.lineTo(25, 105)
- this.context.lineTo(75, 105)
- this.context.lineTo(75, 25)
- this.context.strokeStyle = 'rgb(0,0,255)'
- this.context.stroke()
- })
- }
- .width('100%')
- .height('100%')
- }
- }