HarmonyOS Canvas绘制文本后,使用scale属性缩放后内容模糊

父类组件根据屏幕宽度和当前内容宽度进行了scale缩放操作,即使用.scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })属性。使用Text组件显示文本清晰,使用Canvas组件绘制文本内容模糊。是否有解决方法让父组件进行scale缩放时,让Canvas组件绘制的文本内容清晰。

HarmonyOS
2025-01-09 16:39:16
674浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
FengTianYa

画布的尺寸放大了内容没有重新绘制,被放大后显示模糊是正常的现象,可以使用canvas的scale,设置canvas画布的缩放变换属性,参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-canvasrenderingcontext2d-V5

示例参考如下:

import { MeasureOptions, MeasureText } from '@kit.ArkUI';

@Component
export struct TextCanvas {
  @Prop fontSize: number = 0
  @Prop message: string = ""
  @State textWidth: number = 0
  @State textHeight: number = 0
  @Prop canvasScale: number = 1
  private ctx2D: CanvasRenderingContext2D = new CanvasRenderingContext2D(new RenderingContextSettings(true))

  aboutToAppear(): void {
    this.onMeasureText()
  }

  build() {
    Canvas(this.ctx2D)
      .width(this.textWidth * this.canvasScale)
      .height(this.textHeight * this.canvasScale)
      .onReady(() => {
        this.ctx2D.clearRect(0, 0, this.textWidth, this.textHeight)
        this.ctx2D.scale(this.canvasScale, this.canvasScale)
        this.onDrawText()
      })
    // .scale({ x: this.canvasScale, y: this.canvasScale })
  }

  onDrawText() {
    this.ctx2D.fillStyle = '#000000'
    this.ctx2D.font = this.getTextFontStyle()
    this.ctx2D.fillText(this.message, 0, this.textHeight)
  }

  onMeasureText() {
    let size: SizeOptions = MeasureText.measureTextSize(this.getMeasureOptions())
    this.textWidth = px2vp(size.width as number)
    this.textHeight = px2vp(size.height as number)
  }

  getMeasureOptions(): MeasureOptions {
    return {
      fontSize: this.fontSize + "px",
      textContent: this.message
    }
  }

  getTextFontStyle() {
    //font-style font-weight font-size font-family
    let fontStyleStr = 'normal'
    let fontWeightStr = 'normal'
    let fontSizeStr = this.fontSize + 'px'
    return fontStyleStr + ' ' + fontWeightStr + ' ' + fontSizeStr + ' ' + "HarmonyOS Sans"
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
分享
微博
QQ
微信
回复
2025-01-09 18:21:55


相关问题
HarmonyOS Canvas绘制内容如何更新
621浏览 • 1回复 待解决
Canvas绘制内容如何动态更新
2798浏览 • 1回复 待解决
HarmonyOS 如何清空canvas绘制内容
789浏览 • 1回复 待解决
粘贴文本,IDE把内容自动换行了
958浏览 • 1回复 待解决
HarmonyOS 如何使用canvas绘制虚线
615浏览 • 1回复 待解决
如何使用canvas绘制圆角矩形
1233浏览 • 1回复 待解决
HarmonyOS Canvas绘制圆角
902浏览 • 1回复 待解决
HarmonyOS Canvas横屏定位问题
605浏览 • 1回复 待解决
解决Canvas画布缩放时闪烁
2370浏览 • 1回复 待解决
HarmonyOS Canvas绘制曲线相关
756浏览 • 1回复 待解决
HarmonyOS Canvas绘制圆角矩形
1004浏览 • 1回复 待解决
HarmonyOS Web组件内容缩放问题
1238浏览 • 1回复 待解决