HarmonyOS pixelMap作为参数在父子组件之间传递,传递后无法展示

父组件获得了一个图片 把图片传给子组件。子组件Image无法展示。组件内部用Image可以展示。

断点发现子组件里获得的 pixelMap 的内存地址不同了。

HarmonyOS
2024-12-27 16:46:26
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
fox280

参考如下demo传递pixelMap

import { image } from '@kit.ImageKit';
import { BuilderNode, FrameNode, NodeController } from '@kit.ArkUI';
@Observed
class Params {
  imagePixelMap: image.PixelMap | undefined;
  constructor(imaagePixelMap: image.PixelMap | undefined) {
    this.imagePixelMap = imaagePixelMap;
  }
}
@Component
struct ObjectLinkChild {
  @ObjectLink pixelMapParams: Params;
  build() {
    Column() {
      Text("自定義子組件")
      Image(this.pixelMapParams.imagePixelMap).width(100).height(100)
    }
  }
}
@Builder
function imageBuilder(params: Params) {
  ObjectLinkChild({ pixelMapParams: params })
}
@Entry
@Component
struct ImageExample {
  @State imagePixelMap: image.PixelMap | undefined = undefined;
  @State pixelMapParams: Params = new Params(this.imagePixelMap);
  wrapBuilder: WrappedBuilder<[Params]> = wrapBuilder<[Params]>(imageBuilder);
  async aboutToAppear() {
    this.imagePixelMap = await this.getPixmapFromMedia($r('app.media.app_icon'))
  }
  build() {
    Column() {
      NodeContainer(new MyNodeController(this.imagePixelMap))
        .width(`100%`)
        .height(`100%`)
    }
  }
  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 })
    await imageSource.release()
    return createPixelMap
  }
}

class MyNodeController extends NodeController {
  private rootNode: BuilderNode<[Params]> | null = null;
  private pixelMap: image.PixelMap | undefined = undefined;
  private wrapBuilder: WrappedBuilder<[Params]> = wrapBuilder(imageBuilder);
  constructor(pixelMap: image.PixelMap | undefined) {
    super();
    this.pixelMap = pixelMap;
  }
  setNode(node: BuilderNode<[Params]> | null) {
    this.rootNode = node;
  }
  makeNode(uiContext: UIContext): FrameNode | null {
    if (this.rootNode === null) {
      this.rootNode = new BuilderNode(uiContext);
      this.rootNode.build(this.wrapBuilder, new Params(this.pixelMap));
    }
    return this.rootNode.getFrameNode();
  }
}
分享
微博
QQ
微信
回复
2024-12-27 18:26:19
相关问题
HarmonyOS 怎么把组件作为参数传递
393浏览 • 1回复 待解决
HarmonyOS builder 作为 builder 的参数传递
329浏览 • 1回复 待解决
关于处理父子组件间的事件传递方式
690浏览 • 1回复 待解决
HarmonyOS web组件参数传递报错
351浏览 • 1回复 待解决
Web组件访问本地资源并传递参数
1018浏览 • 1回复 待解决