第76节 绘制文字(fillText 和 stroke)

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

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. 在使用 fillText strokeText 方法之前,需要先设置文本的字体样式(如 font 属性)和颜色(如 fillStyle strokeStyle 属性)。
  2. 文本的默认颜色是黑色,但可以通过设置 fillStyle strokeStyle 属性来改变。
  3. 坐标 (x, y) 指定的是文本的起始绘制位置,其中 y 坐标是文本的基线位置。
  4. maxWidth 参数是可选的,用于限制文本的最大宽度。如果文本宽度超过此值,则会被截断。
通过以上示例和说明,你可以在 HarmonyOS 中使用 TS 语法在画布上绘制填充文本和文本边框。

你可能感兴趣的:(harmonyos,鸿蒙,鸿蒙系统,华为,华为云)