鸿蒙开发-绘制文字(fillText 和 stroke)

在HarmonyOS中,使用TS(TypeScript)语法进行画布(Canvas)开发时,fillTextstrokeText是两个常用的方法,分别用于填充文本和绘制文本边框。以下是这两个方法的详细用法:

fillText 方法

fillText方法用于在画布上绘制填充文本。

  • 语法
fillText(text: string, x: number, y: number, maxWidth?: number): void;
  • 参数**:
    • text:要绘制的文本字符串。
    • x:文本绘制的起始水平坐标(相对于画布)。
    • y:文本绘制的起始垂直坐标(相对于画布,注意文本基线会在此位置)。
    • maxWidth(可选):文本的最大宽度,如果文本宽度超过此值,则会被截断。
  • 示例
@Entry
@Component
struct FillTextExample {
  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 = '30px sans-serif';
          this.context.fillText("Hello HarmonyOS!", 20, 100);
        });
    }
    .width('100%')
    .height('100%');
  }
}

strokeText 方法

strokeText方法用于在画布上绘制文本边框(无填充)。

  • 语法
typescript复制代码

strokeText(text: string, x: number, y: number, maxWidth?: number): void;
  • 参数**:
    • text:要绘制的文本字符串。
    • x:文本绘制的起始水平坐标(相对于画布)。
    • y:文本绘制的起始垂直坐标(相对于画布,注意文本基线会在此位置)。
    • maxWidth(可选):文本的最大宽度,如果文本宽度超过此值,则会被截断。
  • 示例
@Entry
@Component
struct StrokeTextExample {
  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 = '55px sans-serif';
          this.context.strokeText("Hello HarmonyOS!", 20, 60);
        });
    }
    .width('100%')
    .height('100%');
  }
}

注意事项

  1. 在使用fillTextstrokeText方法之前,需要先设置文本的字体样式(如font属性)和颜色(如fillStylestrokeStyle属性)。
  2. 文本的默认颜色是黑色,但可以通过设置fillStylestrokeStyle属性来改变。
  3. 坐标(x, y)指定的是文本的起始绘制位置,其中y坐标是文本的基线位置。
  4. maxWidth参数是可选的,用于限制文本的最大宽度。如果文本宽度超过此值,则会被截断。

通过以上示例和说明,你可以在HarmonyOS中使用TS语法在画布上绘制填充文本和文本边框。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值