openharmony 鸿蒙 arkts-apis-uicontext-componentsnapshot

2026-08-25 浏览 (1)

Class (ComponentSnapshot)

Provides APIs for obtaining component snapshots, including snapshots of components that have been loaded and snapshots of components that have not been loaded yet.

NOTE

  • The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.

  • The initial APIs of this class are supported since API version 12.

  • In the following API examples, you must first use getComponentSnapshot() in UIContext to obtain a ComponentSnapshot instance, and then call the APIs using the obtained instance.

  • Transformation properties such as scaling, translation, and rotation only apply to the child components of the target component. Applying these transformation properties directly to the target component itself has no effect; the snapshot will still display the component as it appears before any transformations are applied.

get12+

get(id: string, callback: AsyncCallback<image.PixelMap>, options?: componentSnapshot.SnapshotOptions): void

Obtains the snapshot of a component that has been loaded based on the provided component ID. This API uses an asynchronous callback to return the result.

NOTE

The snapshot captures content rendered in the last frame. If this API is called when the component triggers an update, the re-rendered content will not be included in the obtained snapshot.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
idstringYesID of the target component.
Note: Off-screen or cached components not mounted in the component tree are not supported.
callbackAsyncCallback<image.PixelMap>YesCallback used to return the result. If the snapshot capture is successful, err is undefined, and data contains the resulting PixelMap. Otherwise, err provides detailed error information.
optionscomponentSnapshot.SnapshotOptionsNoCustom settings of the snapshot.

Error codes

For details about the error codes, see Universal Error Codes, Snapshot Error Codes, and API Call Error Codes.

IDError Message
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001Invalid ID.
160003Unsupported color space or dynamic range mode in snapshot options.

Example

import { image } from '@kit.ImageKit';
import { UIContext } from '@kit.ArkUI';

@Entry
@Component
struct SnapshotExample {
  @State pixmap: image.PixelMap|undefined = undefined;
  uiContext: UIContext = this.getUIContext();

  build() {
    Column() {
      Row() {
        Image(this.pixmap).width(150).height(150).border({ color: Color.Black, width: 2 }).margin(5)
        // Replace $r('app.media.img') with the image resource file you use.
        Image($r('app.media.img'))
          .autoResize(true)
          .width(150)
          .height(150)
          .margin(5)
          .id("root")
      }

      Button("click to generate UI snapshot")
        .onClick(() => {
          this.uiContext.getComponentSnapshot().get("root", (error: Error, pixmap: image.PixelMap) => {
            if (error) {
              console.error(`error: ${JSON.stringify(error)}`);
              return;
            }
            this.pixmap = pixmap;
          }, { scale: 2, waitUntilRenderFinished: true });
        }).margin(10)
    }
    .width('100%')
    .height('100%')
    .alignItems(HorizontalAlign.Center)
  }
}

Getscreent

get12+

get(id: string, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap>

Obtains the snapshot of a component that has been loaded based on the provided component ID. This API uses a promise to return the result.

NOTE

The snapshot captures content rendered in the last frame. If this API is called when the component triggers an update, the re-rendered content will not be included in the obtained snapshot.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
idstringYesID of the target component.
Note: Off-screen or cached components not mounted in the component tree are not supported.
optionscomponentSnapshot.SnapshotOptionsNoCustom settings of the snapshot.

Return value

TypeDescription
Promise<image.PixelMap>Promise used to return the snapshot object.

Error codes

For details about the error codes, see Universal Error Codes, Snapshot Error Codes, and API Call Error Codes.

IDError Message
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001Invalid ID.
160003Unsupported color space or dynamic range mode in snapshot options.

Example

import { image } from '@kit.ImageKit';
import { UIContext } from '@kit.ArkUI';

@Entry
@Component
struct SnapshotExample {
  @State pixmap: image.PixelMap|undefined = undefined;
  uiContext: UIContext = this.getUIContext();

  build() {
    Column() {
      Row() {
        Image(this.pixmap).width(150).height(150).border({ color: Color.Black, width: 2 }).margin(5)
        // Replace $r('app.media.icon') with the image resource file you use.
        Image($r('app.media.icon'))
          .autoResize(true)
          .width(150)
          .height(150)
          .margin(5)
          .id("root")
      }

      Button("click to generate UI snapshot")
        .onClick(() => {
          this.uiContext.getComponentSnapshot()
            .get("root", { scale: 2, waitUntilRenderFinished: true })
            .then((pixmap: image.PixelMap) => {
              this.pixmap = pixmap;
            })
            .catch((err: Error) => {
              console.error(`error: ${err}`);
            })
        }).margin(10)
    }
    .width('100%')
    .height('100%')
    .alignItems(HorizontalAlign.Center)
  }
}

createFromBuilder12+

createFromBuilder(builder: CustomBuilder, callback: AsyncCallback<image.PixelMap>, delay?: number, checkImageStatus?: boolean, options?: componentSnapshot.SnapshotOptions): void

Captures a snapshot of an offscreen-rendered component created from a CustomBuilder. This API uses an asynchronous callback to return the result.

NOTE

  • Due to the need to wait for the component to be built and rendered, there is a delay of not more than 500 ms in the callback for off-screen snapshot capturing. Therefore, this API is not recommended for performance-sensitive scenarios.

  • If a component is on a time-consuming task, for example, an Image or Web component that is loading online images, its loading may be still in progress when this API is called. In this case, the output snapshot does not represent the component in the way it looks when the loading is successfully completed.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
builderCustomBuilderYesBuilder of the custom component.
Note: The global builder is not supported.
If the root component of the builder has a width or height of zero, the snapshot operation will fail with error code 100001.
callbackAsyncCallback<image.PixelMap>YesCallback used to return the result. If the snapshot capture is successful, err is undefined, and data contains the resulting PixelMap. Otherwise, err provides detailed error information. The coordinates and size of the offscreen component's drawing area can be obtained through the callback.
delaynumberNoDelay time for triggering the screenshot command. When the layout includes an image component, it is necessary to set a delay time to allow the system to decode the image resources. The decoding time is subject to the resource size. In light of this, whenever possible, use pixel map resources that do not require decoding.
When PixelMap resources are used or when syncLoad is set to true for the Image component, you can set delay to 0 to forcibly capture snapshots without waiting. This delay time does not refer to the time from the API call to the return: As the system needs to temporarily construct the passed-in builder offscreen, the return time is usually longer than this delay.
Note: In the builder passed in, state variables should not be used to control the construction of child components. If they are used, they should not change when the API is called, so as to avoid unexpected snapshot results.
Default value: 300
Unit: ms
Value range: [0, +∞). If the value is less than 0, the default value is used.
checkImageStatusbooleanNoWhether to verify the image decoding status before taking a snapshot. If the value is true, the system checks whether all Image components have been decoded before taking the snapshot. If the check is not completed, the system aborts the snapshot and returns an exception.
Default value: false.
optionscomponentSnapshot.SnapshotOptionsNoCustom settings of the snapshot.

Error codes

For details about the error codes, see Universal Error Codes, Snapshot Error Codes, and API Call Error Codes.

IDError Message
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001The builder is not a valid build function.
160001An image component in builder is not ready for taking a snapshot. The check for the ready state is required when the checkImageStatus option is enabled.
160003Unsupported color space or dynamic range mode in snapshot options.
160004isAuto(true) is not supported for offscreen node snapshots.

Example

import { image } from '@kit.ImageKit';
import { UIContext } from '@kit.ArkUI';

@Entry
@Component
struct ComponentSnapshotExample {
  @State pixmap: image.PixelMap|undefined = undefined;
  uiContext: UIContext = this.getUIContext();

  @Builder
  RandomBuilder() {
    Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
      Text('Test menu item 1')
        .fontSize(20)
        .width(100)
        .height(50)
        .textAlign(TextAlign.Center)
      Divider().height(10)
      Text('Test menu item 2')
        .fontSize(20)
        .width(100)
        .height(50)
        .textAlign(TextAlign.Center)
    }
    .width(100)
    .id("builder")
  }

  build() {
    Column() {
      Button("click to generate UI snapshot")
        .onClick(() => {
          this.uiContext.getComponentSnapshot().createFromBuilder(() => {
            this.RandomBuilder()
          },
            (error: Error, pixmap: image.PixelMap) => {
              if (error) {
                console.error(`error: ${JSON.stringify(error)}`);
                return;
              }
              this.pixmap = pixmap;
            }, 320, true, { scale: 2, waitUntilRenderFinished: true });
        })
      Image(this.pixmap)
        .margin(10)
        .height(200)
        .width(200)
        .border({ color: Color.Black, width: 2 })
    }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300)
  }
}

createFromBuilder12+

createFromBuilder(builder: CustomBuilder, delay?: number, checkImageStatus?: boolean, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap>

Captures a snapshot of an offscreen-rendered component created from a CustomBuilder. This API uses a promise to return the result.

NOTE

  • Due to the need to wait for the component to be built and rendered, there is a delay of not more than 500 ms in the callback for off-screen snapshot capturing. Therefore, this API is not recommended for performance-sensitive scenarios.

  • If a component is on a time-consuming task, for example, an Image or Web component that is loading online images, its loading may be still in progress when this API is called. In this case, the output snapshot does not represent the component in the way it looks when the loading is successfully completed.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
builderCustomBuilderYesBuilder of the custom component.
Note: The global builder is not supported.
If the root component of the builder has a width or height of zero, the snapshot operation will fail with error code 100001.
delaynumberNoDelay time for triggering the screenshot command. When the layout includes an image component, it is necessary to set a delay time to allow the system to decode the image resources. The decoding time is subject to the resource size. In light of this, whenever possible, use pixel map resources that do not require decoding.
When PixelMap resources are used or when syncLoad is set to true for the Image component, you can set delay to 0 to forcibly capture snapshots without waiting. This delay time does not refer to the time from the API call to the return: As the system needs to temporarily construct the passed-in builder offscreen, the return time is usually longer than this delay.
Note: In the builder passed in, state variables should not be used to control the construction of child components. If they are used, they should not change when the API is called, so as to avoid unexpected snapshot results.
Default value: 300
Unit: ms
Value range: [0, +∞). If the value is less than 0, the default value is used.
checkImageStatusbooleanNoWhether to verify the image decoding status before taking a snapshot. If the value is true, the system checks whether all Image components have been decoded before taking the snapshot. If the check is not completed, the system aborts the snapshot and returns an exception.
Default value: false.
optionscomponentSnapshot.SnapshotOptionsNoCustom settings of the snapshot.

Return value

TypeDescription
Promise<image.PixelMap>Promise used to return the snapshot object.

Error codes

For details about the error codes, see Universal Error Codes, Snapshot Error Codes, and API Call Error Codes.

IDError Message
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001The builder is not a valid build function.
160001An image component in builder is not ready for taking a snapshot. The check for the ready state is required when the checkImageStatus option is enabled.
160003Unsupported color space or dynamic range mode in snapshot options.
160004isAuto(true) is not supported for offscreen node snapshots.

Example

import { image } from '@kit.ImageKit';
import { UIContext } from '@kit.ArkUI';

@Entry
@Component
struct ComponentSnapshotExample {
  @State pixmap: image.PixelMap|undefined = undefined;
  uiContext: UIContext = this.getUIContext();

  @Builder
  RandomBuilder() {
    Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
      Text('Test menu item 1')
        .fontSize(20)
        .width(100)
        .height(50)
        .textAlign(TextAlign.Center)
      Divider().height(10)
      Text('Test menu item 2')
        .fontSize(20)
        .width(100)
        .height(50)
        .textAlign(TextAlign.Center)
    }
    .width(100)
    .id("builder")
  }

  build() {
    Column() {
      Button("click to generate UI snapshot")
        .onClick(() => {
          this.uiContext.getComponentSnapshot()
            .createFromBuilder(() => {
              this.RandomBuilder()
            }, 320, true, { scale: 2, waitUntilRenderFinished: true })
            .then((pixmap: image.PixelMap) => {
              this.pixmap = pixmap;
            })
            .catch((err: Error) => {
              console.error(`error: ${err}`);
            })
        })
      Image(this.pixmap)
        .margin(10)
        .height(200)
        .width(200)
        .border({ color: Color.Black, width: 2 })
    }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300)
  }
}

getSync12+

getSync(id: string, options?: componentSnapshot.SnapshotOptions): image.PixelMap

Obtains the snapshot of a component that has been loaded based on the provided component ID. This API synchronously returns a PixelMap after completing the capture. Note that this API blocks the main thread and has a 3-second timeout. If the operation exceeds this limit, it throws an exception. Use with caution in performance-critical scenarios.

NOTE

The snapshot captures content rendered in the last frame. If this API is called when the component triggers an update, the re-rendered content will not be included in the obtained snapshot.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
idstringYesID of the target component.
Note: Off-screen or cached components not mounted in the component tree are not supported.
optionscomponentSnapshot.SnapshotOptionsNoCustom settings of the snapshot.

Return value

TypeDescription
image.PixelMapPromise used to return the result.

Error codes

For details about the error codes, see Universal Error Codes, Snapshot Error Codes, and API Call Error Codes.

IDError Message
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001Invalid ID.
160002Timeout.
160003Unsupported color space or dynamic range mode in snapshot options.

Example

import { image } from '@kit.ImageKit';

@Entry
@Component
struct SnapshotExample {
  @State pixmap: image.PixelMap|undefined = undefined;

  build() {
    Column() {
      Row() {
        Image(this.pixmap).width(150).height(150).border({ color: Color.Black, width: 2 }).margin(5)
        // Replace $r('app.media.img') with the image resource file you use.
        Image($r('app.media.img'))
          .autoResize(true)
          .width(150)
          .height(150)
          .margin(5)
          .id("root")
      }

      Button("click to generate UI snapshot")   
        .onClick(() => {
          try {
            let pixelmap =
              this.getUIContext().getComponentSnapshot().getSync("root", { scale: 2, waitUntilRenderFinished: true });
            this.pixmap = pixelmap;
          } catch (error) {
            console.error(`getSync errorCode: ${error.code} message: ${error.message}`);
          }
        }).margin(10)
    }
    .width('100%')
    .height('100%')
    .alignItems(HorizontalAlign.Center)
  }
}

getWithUniqueId15+

getWithUniqueId(uniqueId: number, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap>

Obtains the snapshot of a component that has been loaded based on the provided uniqueId. This API uses a promise to return the result.

NOTE

The snapshot captures content rendered in the last frame. If this API is called when the component triggers an update, the re-rendered content will not be included in the obtained snapshot.

Atomic service API: This API can be used in atomic services since API version 15.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
uniqueIdnumberYesUnique ID of the target component. The unique ID of the FrameNode can be obtained via the getUniqueId API.
Note: Off-screen or cached components not mounted in the component tree are not supported.
optionscomponentSnapshot.SnapshotOptionsNoCustom settings of the snapshot.

Return value

TypeDescription
Promise<image.PixelMap>Promise used to return the snapshot object.

Error codes

For details about the error codes, see Universal Error Codes, Snapshot Error Codes, and API Call Error Codes.

IDError Message
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001Invalid ID.
160003Unsupported color space or dynamic range mode in snapshot options.

Example

import { NodeController, FrameNode, typeNode } from '@kit.ArkUI';
import { image } from '@kit.ImageKit';
import { UIContext } from '@kit.ArkUI';

class MyNodeController extends NodeController {
  public node: FrameNode|null = null;
  public imageNode: FrameNode|null = null;

  makeNode(uiContext: UIContext): FrameNode|null {
    this.node = new FrameNode(uiContext);
    this.node.commonAttribute.width('100%').height('100%');

    let image = typeNode.createNode(uiContext, 'Image');
    // Replace $r('app.media.img') with the image resource file you use.
    image.initialize($r('app.media.img')).width('100%').height('100%').autoResize(true);
    this.imageNode = image;

    this.node.appendChild(image);
    return this.node;
  }
}

@Entry
@Component
struct SnapshotExample {
  private myNodeController: MyNodeController = new MyNodeController();
  @State pixmap: image.PixelMap|undefined = undefined;

  build() {
    Column() {
      Row() {
        Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)
        NodeContainer(this.myNodeController).width(200).height(200).margin(5)
      }

      Button("UniqueId get snapshot")
        .onClick(() => {
          try {
            this.getUIContext()
              .getComponentSnapshot()
              .getWithUniqueId(this.myNodeController.imageNode?.getUniqueId(),
                { scale: 2, waitUntilRenderFinished: true })
              .then((pixmap: image.PixelMap) => {
                this.pixmap = pixmap;
              })
              .catch((err: Error) => {
                console.error(`error: ${err}`);
              })
          } catch (error) {
            console.error(`UniqueId get snapshot Error: ${JSON.stringify(error)}`);
          }
        }).margin(10)
    }
    .width('100%')
    .height('100%')
    .alignItems(HorizontalAlign.Center)
  }
}

getSyncWithUniqueId15+

getSyncWithUniqueId(uniqueId: number, options?: componentSnapshot.SnapshotOptions): image.PixelMap

Obtains the snapshot of a component that has been loaded based on the provided uniqueId. This API synchronously waits for the snapshot to complete and returns a PixelMap object.

NOTE

The snapshot captures content rendered in the last frame. If this API is called when the component triggers an update, the re-rendered content will not be included in the obtained snapshot.

Atomic service API: This API can be used in atomic services since API version 15.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
uniqueIdnumberYesUnique ID of the target component. The unique ID of the FrameNode can be obtained via the getUniqueId API.
Note: Off-screen or cached components not mounted in the component tree are not supported.
optionscomponentSnapshot.SnapshotOptionsNoCustom settings of the snapshot.

Return value

TypeDescription
image.PixelMapPromise used to return the result.

Error codes

For details about the error codes, see Universal Error Codes, Snapshot Error Codes, and API Call Error Codes.

IDError Message
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001Invalid ID.
160002Timeout.
160003Unsupported color space or dynamic range mode in snapshot options.

Example

import { NodeController, FrameNode, typeNode } from '@kit.ArkUI';
import { image } from '@kit.ImageKit';
import { UIContext } from '@kit.ArkUI';
// Create a FrameNode node that contains an Image component.
class MyNodeController extends NodeController {
  public node: FrameNode|null = null;
  public imageNode: FrameNode|null = null;
  // Build a custom node, create the root node FrameNode, add a child node Image, and configure the Image resource and style.
  makeNode(uiContext: UIContext): FrameNode|null {
    this.node = new FrameNode(uiContext);
    this.node.commonAttribute.width('100%').height('100%');

    let image = typeNode.createNode(uiContext, 'Image');
    // Replace $r('app.media.img') with the image resource file you use.
    image.initialize($r('app.media.img')).width('100%').height('100%').autoResize(true);
    this.imageNode = image;

    this.node.appendChild(image);
    return this.node;
  }
}

@Entry
@Component
struct SnapshotExample {
  private myNodeController: MyNodeController = new MyNodeController();
  @State pixmap: image.PixelMap|undefined = undefined;

  build() {
    Column() {
      Row() {
        Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)
        NodeContainer(this.myNodeController).width(200).height(200).margin(5)
      }

      Button("UniqueId getSync snapshot")
        .onClick(() => {
          try {
            // Generate a component snapshot synchronously by node ID, with the zoom ratio of 2. The snapshot is generated after the rendering is complete.
            this.pixmap = this.getUIContext()
              .getComponentSnapshot()
              .getSyncWithUniqueId(this.myNodeController.imageNode?.getUniqueId(),
                { scale: 2, waitUntilRenderFinished: true });
          } catch (error) {
            console.error(`UniqueId getSync snapshot Error: ${JSON.stringify(error)}`);
          }
        }).margin(10)
    }
    .width('100%')
    .height('100%')
    .alignItems(HorizontalAlign.Center)
  }
}

createFromComponent18+

createFromComponent<T extends Object>(content: ComponentContent<T>, delay?: number, checkImageStatus?: boolean, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap>

Captures a snapshot of the provided component content. This API uses a promise to return the result.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

NameTypeMandatoryDescription
contentComponentContent<T>YesComponent content to be captured. This is the content currently displayed in the UIContext.
delaynumberNoDelay time for triggering the screenshot command. When the layout includes an image component, it is necessary to set a delay time to allow the system to decode the image resources. The decoding time is subject to the resource size. In light of this, whenever possible, use pixel map resources that do not require decoding.
When PixelMap resources are used or when syncLoad is set to true for the Image component, you can set delay to 0 to forcibly capture snapshots without waiting. This delay time does not refer to the time from the API call to the return: As the system needs to temporarily construct the passed-in builder offscreen, the return time is usually longer than this delay.
Note: In the builder passed in, state variables should not be used to control the construction of child components. If they are used, they should not change when the API is called, so as to avoid unexpected snapshot results.
Value range: [0, +∞). If the value is less than 0, the default value is used.
Default value: 300
Unit: ms
checkImageStatusbooleanNoWhether to verify the image decoding status before taking a snapshot. If the value is true, the system checks whether all Image components have been decoded before taking the snapshot. If the check is not completed, the system aborts the snapshot and returns an exception.
Default value: false.
optionscomponentSnapshot.SnapshotOptionsNoCustom settings of the snapshot. You can specify the scale ratio for the pixelmap during rendering and whether to force the system to complete all rendering commands before taking the snapshot.

Return value

TypeDescription
Promise<image.PixelMap>Promise used to return the snapshot object.

Error codes

For details about the error codes, see Universal Error Codes, Snapshot Error Codes, and API Call Error Codes.

IDError Message
401Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001The builder is not a valid build function.
160001An image component in builder is not ready for taking a snapshot. The check for the ready state is required when the checkImageStatus option is enabled.
160003Unsupported color space or dynamic range mode in snapshot options.
160004isAuto(true) is not supported for offscreen node snapshots.

Example

import { image } from '@kit.ImageKit';
import { ComponentContent } from '@kit.ArkUI';

class Params {
  text: string|undefined|null = "";

  constructor(text: string|undefined|null) {
    this.text = text;
  }
}

@Builder
function buildText(params: Params) {
  ReusableChildComponent({ text: params.text })
}

@Component
struct ReusableChildComponent {
  @Prop text: string|undefined|null = "";

  aboutToReuse(params: Record<string, object>) {
    console.info(`ReusableChildComponent Reusable ${JSON.stringify(params)}`);
  }

  aboutToRecycle(): void {
    console.info(`ReusableChildComponent aboutToRecycle ${this.text}`);
  }

  build() {
    Column() {
      Text(this.text)
        .fontSize(90)
        .fontWeight(FontWeight.Bold)
        .margin({ bottom: 36 })
        .width('100%')
        .height('100%')
    }.backgroundColor('#FFF0F0F0')
  }
}

@Entry
@Component
struct Index {
  @State pixmap: image.PixelMap|undefined = undefined;
  @State message: string|undefined|null = "hello";
  uiContext: UIContext = this.getUIContext();

  build() {
    Row() {
      Column() {
        Button("Create Component Snapshot")
          .onClick(() => {
            let uiContext = this.getUIContext();
            let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message));
            this.uiContext.getComponentSnapshot()
              .createFromComponent(contentNode
                , 320, true, { scale: 2, waitUntilRenderFinished: true })
              .then((pixmap: image.PixelMap) => {
                this.pixmap = pixmap;
              })
              .catch((err: Error) => {
                console.error(`error: ${err}`);
              })
          })
        Image(this.pixmap)
          .margin(10)
          .height(200)
          .width(200)
          .border({ color: Color.Black, width: 2 })
      }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300)
    }
    .width('100%')
    .height('100%')
  }
}

你可能感兴趣的鸿蒙文章

openharmony 鸿蒙 arkts-apis-uicontext-contextmenucontroller

openharmony 鸿蒙 errorcode-canvas

openharmony 鸿蒙 capi-oh-nativexcomponent-native-xcomponent-oh-nativexcomponent

openharmony 鸿蒙 errorcode-bindSheet

openharmony 鸿蒙 js-apis-arkui-uiExtension-sys

openharmony 鸿蒙 capi-arkui-accessibility-arkui-accessibilityeventinfo

openharmony 鸿蒙 capi-arkui-rendernodeutils

openharmony 鸿蒙 js-apis-arkui-node

openharmony 鸿蒙 capi-native-node-h

openharmony 鸿蒙 capi-arkui-nativemodule-arkui-listitemswipeactionitem

  • 所属分类: 后端技术
  • 本文标签: 鸿蒙 软件
  • 版权声明: 本文链接 https://seaxiang.com/blog/1kbeB2NO