HarmonyOS Canvas绘制的颜色无法使用颜色资源?

Canvas绘制的颜色类型无法使用$r,需要通过resourceManager.getColorSync转换成number或者string才行。

项目中大量重复使用的颜色,想使用静态变量存储。

但resourceManager需要使用上下文context,如果静态变量文件所在的库在EntryAbility中有引用(如要处理onForeground事件),静态变量会在上下文初始化之前进行加载,导致启动崩溃。

有没有更好的解决方案可以支持使用静态变量存储颜色值

阅读 427
1 个回答

试一下这个demo

EntryAbility.ets

onForeground(): void {
  // Ability has brought to foreground
  hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
  console.info('app is foreground');
  let context = GlobalContext.getContext().getObject('Context') as common.Context
  let a = context?.resourceManager.getColorSync($r('app.color.start_window_background'))
  console.info('onForeground: '+a?.toString())
}

Index.ets

// xxx.ets
import { GlobalContext } from './GlobalContext';
import { common } from '@kit.AbilityKit';

@Entry
@Component
struct Index {
  private settings: RenderingContextSettings = new RenderingContextSettings(true)
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600)

  aboutToAppear(): void {
    let context = getContext(this)
    GlobalContext.getContext().setObject('Context', context)
    let context1 = GlobalContext.getContext().getObject('Context') as common.Context
    let a = context1?.resourceManager.getColorSync($r('app.color.start_window_background'))
    console.info('aboutToAppear: '+a?.toString())
  }

  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
      Canvas(this.context)
        .width('100%')
        .height('100%')
        .backgroundColor('#ffff00')
        .onReady(() => {
          let a = getContext(this).resourceManager.getColorSync($r('app.color.start_window_background'))
          let offContext = this.offCanvas.getContext("2d", this.settings)
          offContext.shadowBlur = 30
          offContext.shadowColor = a.toString()
          offContext.fillStyle = a.toString()
          offContext.fillRect(30, 30, 100, 100)
          let image = this.offCanvas.transferToImageBitmap()
          this.context.transferFromImageBitmap(image)
        })
    }
    .width('100%')
    .height('100%')
  }
}

GlobalContext.ets

export class GlobalContext {
  private constructor() {
  }

  private static instance: GlobalContext;
  private _objects = new Map<string, Object>();

  public static getContext(): GlobalContext {
    if (!GlobalContext.instance) {
      GlobalContext.instance = new GlobalContext();
    }
    return GlobalContext.instance;
  }

  getObject(value: string): Object | undefined {
    return this._objects.get(value);
  }

  setObject(key: string, objectClass: Object): void {
    this._objects.set(key, objectClass);
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进