HarmonyOS 怎么设置自定义字体并获取自定义字体的宽度,高度?

需要使用自定义字体时,发现用以下代码,取到的字体是:HarmonyOS Sans SC,怎么才能设置自定义字体并获取自定义字体的宽度,高度信息?

let font=new drawing.Font(); 
font.setTypeface(new drawing.Typeface()) 
console.info("ddd",font.getTypeface().getFamilyName());
阅读 596
1 个回答

关于自定义字体:自定义字体支持使用网络字体,引入ttf文件后,有对应的Iconfont才能显示,参考下面代码:

import font from ‘@ohos.font’;
@Entry
@Component
struct Index {
  @State message: string = ‘Hello World’;

  aboutToAppear() {

    font.registerFont({
      familyName: ‘iconfont’,
      familySrc: $rawfile(‘iconfont.ttf’)
    })
  }

  build() {
    Row() {
      Column() {
        Text("\ue6fb")
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .fontFamily(“iconfont”)
        Image(“xxxx”)
        .alt($r(“app.media.startIcon”))
        .width(300)
          .height(300)
          .onError(() => {
            console.log(“图片加载失败。。。”)
          })
      }
      .width(‘100%’)
    }
    .height(‘100%’)
  }
}

参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-font-V5

关于获取自定义字体宽高,可以使用measure.measureText方法,再结合fontSize, fontStyle和fontWeight使用进行文本测量:可参考如下代码:

import font from ‘@ohos.font’
import measure from ‘@ohos.measure’
@Entry
@Component
struct Index {
  @State text:string = ‘123456’
  @State familyName2:string = ‘20th_bold’
  @State textWidth: number = measure.measureText({
    textContent: this.text,
    fontFamily: this.familyName2,
    fontStyle:FontStyle.Normal,
    fontWeight: 100
  })
  @State textWidth2: number = measure.measureText({
    textContent: this.text,
    fontFamily: this.familyName2,
    fontStyle: FontStyle.Italic,
    fontWeight: FontWeight.Bolder
  })
  aboutToAppear(): void {
    font.registerFont({
      familyName: this.familyName2,
      familySrc: $rawfile(‘font/20th_bold.ttf’)
    })
  }

  build() {
    Row() {
      Column() {
        Text(this.text)
          .fontSize(30)
          .fontFamily(‘20th_bold’)
        .fontColor(’#333333’)
        .fontWeight(400)
        Text(我是自定义字体的测量宽度1:${this.textWidth}) //181
        Text(我是自定义字体的测量宽度2:${this.textWidth2}) //207
      }
      .width(‘100%’)
    }
    .height(‘100%’)
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进