UserGradeTextSpan.ets 2.28 KB
import { GradeSpan } from './span/GradeSpan';
import { image } from '@kit.ImageKit';
import { LengthMetrics } from '@kit.ArkUI';
import { StringUtils } from 'wdKit';

@Component
export struct UserGradeTextSpan{
  @Watch('contentChange')  @Prop nameContent:string = ""
  @Watch('contentChange') @Prop gradeContent:string = ""
  @Watch('contentChange') @Prop gradeWidth:number = 50

  taskId:number = -1

  customSpan3: GradeSpan | undefined = undefined;
  style1: MutableStyledString | undefined = undefined;

  imagePixelMap: image.PixelMap | undefined = undefined;

  textController: TextController = new TextController();

  private async getPixmapFromMedia(resource: Resource) {
    let unit8Array = await getContext(this)?.resourceManager?.getMediaContent({
      bundleName: resource.bundleName,
      moduleName: resource.moduleName,
      id: resource.id
    });
    let imageSource = image.createImageSource(unit8Array.buffer.slice(0, unit8Array.buffer.byteLength));
    let createPixelMap: image.PixelMap = await imageSource.createPixelMap({
      desiredPixelFormat: image.PixelMapFormat.RGBA_8888,
      desiredSize: { width: vp2px(this.gradeWidth), height: vp2px(18) }
    });
    await imageSource.release();
    return createPixelMap;
  }

  contentChange(){
    if(this.taskId != -1){
      clearTimeout(this.taskId)
    }
    this.taskId = setTimeout(() => {
      this.createSpan()
    }, 100);

  }

  async createSpan(){
    if(StringUtils.isEmpty(this.nameContent)){
      return
    }
    this.imagePixelMap = await this.getPixmapFromMedia($r('app.media.my_grade_bg'))
    this.customSpan3 = new GradeSpan(this.gradeContent, this.gradeWidth, 18,this.imagePixelMap);
    this.style1 = new MutableStyledString(this.customSpan3);

    let name:MutableStyledString = new MutableStyledString(this.nameContent, [
      {
        start: 0,
        length: 100,
        styledKey: StyledStringKey.FONT,
        styledValue: new TextStyle({ fontColor: Color.White,fontWeight: 500,fontSize: LengthMetrics.px(vp2px(20)) })
      }])

    name.appendStyledString(new StyledString(this.customSpan3))
    this.textController.setStyledString(name)
  }


  aboutToAppear() {
    this.createSpan()
  }

  build() {
    Text(undefined, { controller: this.textController })
      .copyOption(CopyOptions.InApp)
      .maxLines(2)
  }
}