以自定义弹窗组件为示例:
使用componentSnapshot.get进行截图的页面代码:
import { image } from '@kit.ImageKit'; @Entry @Component struct SnapShotExample { @State items: string[] = ['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']; @State pixMap: image.PixelMap | undefined = undefined; @State mText: string = '我是内容'; // dialogController只可以传入pixMap,options与buffer无效果 dialogController: CustomDialogController = new CustomDialogController({ builder: CustomDialogComponent({ pixelMap: this.pixMap, text: this.mText }) }); build() { Column() { Text('我是标题') .width('100%') .height(100) .textAlign(TextAlign.Center) .fontColor(Color.Black) .backgroundColor('#f1f3f5'); Scroll() { Column() { ForEach(this.items, (item: string) => { Text('我是内容' + item).width('100%').height(50).fontColor('#0a59f7'); }); }.width('100%').padding(24); }.width('100%').layoutWeight(1).id('mainScroll'); Blank().width('100%').height(1).backgroundColor(Color.Black); // 展示截屏图片 Image(this.pixMap).width('100%').layoutWeight(0.5).objectFit(ImageFit.Contain); Button('点击截图').width(100).height(45).onClick(() => { // 核心方法,获取已加载的组件的截图 let snapShot = this.getUIContext().getComponentSnapshot(); snapShot.get('mainScroll', { scale: 0.8, waitUntilRenderFinished: true }) .then((pixMap: image.PixelMap) => { // 用pixMap方式,同时可以对比测试 this.pixMap = pixMap; // 打开弹窗 this.dialogController.open(); this.mText = '截图成功'; }) .catch((err: Error) => { console.error(`截图失败:${err}`); }); }); }.width('100%').height('100%'); } }
弹窗组件代码:
// 自定义弹窗组件,用于展示截屏图片 @CustomDialog struct CustomDialogComponent { controller?: CustomDialogController; pixelMap: image.PixelMap | undefined; /*= undefined*/ @Prop text: string | undefined; build() { Column() { Text(this.text).width('100%').height(50).textAlign(TextAlign.Center).fontColor('#0a59f7'); // 展示截屏图片 Image(this.pixelMap).width(200).height(500).objectFit(ImageFit.Contain); Button('关闭') .width(100) .height(45) .backgroundColor('#0a59f7') .onClick(() => { // 关闭弹窗 this.controller?.close(); }) .margin({ top: 10 }); }; } }