harmony-utils之SnapshotUtil,截图相关工具类

简介: harmony-utils是一款专为HarmonyOS开发的高效工具库,提供丰富的实用功能,助力开发者快速构建鸿蒙应用。其中的SnapshotUtil类专注于截图功能,支持组件截图、自定义Builder渲染截图、窗口截图及系统截屏监听等操作,极大提升了开发效率与应用交互体验。

harmony-utils之SnapshotUtil,截图相关工具类

harmony-utils 简介与说明


harmony-utils 一款功能丰富且极易上手的HarmonyOS工具库,借助众多实用工具类,致力于助力开发者迅速构建鸿蒙应用。其封装的工具涵盖了APP、设备、屏幕、授权、通知、线程间通信、弹框、吐司、生物认证、用户首选项、拍照、相册、扫码、文件、日志,异常捕获、字符、字符串、数字、集合、日期、随机、base64、加密、解密、JSON等一系列的功能和操作,能够满足各种不同的开发需求。
picker_utils 是harmony-utils拆分出来的一个子库,包含PickerUtil、PhotoHelper、ScanUtil。

下载安装
ohpm i @pura/harmony-utils
ohpm i @pura/picker_utils

  //全局初始化方法,在UIAbility的onCreate方法中初始化 AppUtil.init()
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    AppUtil.init(this.context);
  }

API方法与使用


get 获取已加载的组件的截图,传入组件的组件id,找到对应组件进行截图
let pixelMap1 = await SnapshotUtil.get('snapshot_id1');
let pixelMap2 = SnapshotUtil.getSync('snapshot_id2');
createFromBuilder 在应用后台渲染CustomBuilder自定义组件,并输出其截图
SnapshotUtil.createFromBuilder(() => {
  this.RandomBuilder()
}).then((pixelMap) => {
  Utils.showSheetImg(pixelMap);
}).catch((err: BusinessError) => {
  ToastUtil.showToast("组件生成图片异常!");
});

@Builder
RandomBuilder() {
  Column() {
    Text("Builder截图")
      .fontSize(20)
      .fontWeight(FontWeight.Bold)
      .fontStyle(FontStyle.Italic)
      .margin({ top: 20 })
    Image($r("app.media.test_as4"))
      .margin({ top: 30, bottom: 10 })
      .padding(10)
      .width('95%')
      .backgroundColor(Color.Pink)
  }
  .backgroundColor(Color.Blue)
  .padding(10)
  .width('100%')
  .aspectRatio(1)
  .margin({ top: 50 })
  .id("rBuilder")
}
snapshot 获取窗口截图,使用Promise异步回调
let pixelMap3 = await SnapshotUtil.snapshot();
onSnapshotListener 开启系统截屏事件的监听
SnapshotUtil.onSnapshotListener(() => {
  ToastUtil.showToast("系统截图了!");
  LogUtil.error("系统截图了!");
});
removeSnapshotListener 关闭系统截屏事件的监听
 SnapshotUtil.removeSnapshotListener();
 SnapshotUtil.removeSnapshotListener(snapshotCallBack);

示例代码


import {
    router } from '@kit.ArkUI';
import {
    LogUtil, SnapshotUtil, ToastUtil } from '@pura/harmony-utils';
import {
    DescribeBean } from '../../model/DescribeBean';
import {
    BusinessError } from '@kit.BasicServicesKit';
import {
    MockSetup } from '@ohos/hamock';
import {
    TitleBarView } from '../../component/TitleBarView';
import {
    Utils } from '../../utils/Utils';

/**
 * 组件截图和窗口截图工具类
 */
@Entry
@Component
struct Index {
   
  private scroller: Scroller = new Scroller();
  @State describe: DescribeBean = router.getParams() as DescribeBean;
  private snapshotCallBack: VoidCallback = () => {
    //系统截图监听回调
    ToastUtil.showToast("您已成功截图!");
    LogUtil.error("您已成功截图!");
  }

  @MockSetup
  mock() {
   
    this.describe = new DescribeBean("SnapshotUtil", "组件截图和窗口截图工具类");
  }

  build() {
   
    Column() {
   
      TitleBarView({
    describe: this.describe })
      Divider()
      Scroll(this.scroller) {
   
        Column() {
   
          Button("get()")
            .btnStyle()
            .onClick(async () => {
   
              let pixelMap1 = await SnapshotUtil.get('snapshot_id1');
              Utils.showSheetImg(pixelMap1);
            })
          Button("getSync()")
            .btnStyle()
            .onClick(() => {
   
              let pixelMap1 = SnapshotUtil.getSync('snapshot_id2');
              Utils.showSheetImg(pixelMap1);
            })
          Button("createFromBuilder()")
            .btnStyle()
            .onClick(() => {
   
              SnapshotUtil.createFromBuilder(() => {
   
                this.RandomBuilder()
              }).then((pixelMap) => {
   
                Utils.showSheetImg(pixelMap);
              }).catch((err: BusinessError) => {
   
                LogUtil.error("createFromBuilder-异常信息:\n" + JSON.stringify(err));
                ToastUtil.showToast("组件生成图片异常!");
              });
            })
          Button("snapshot()")
            .btnStyle()
            .onClick(async () => {
   
              let pixelMap3 = await SnapshotUtil.snapshot();
              Utils.showSheetImg(pixelMap3);
            })
          Button("onSnapshotListener()")
            .btnStyle()
            .onClick(() => {
   
              SnapshotUtil.onSnapshotListener(() => {
   
                ToastUtil.showToast("系统截图了!");
                LogUtil.error("系统截图了!");
              });
            })
          Button("removeSnapshotListener()")
            .btnStyle()
            .onClick(() => {
   
              SnapshotUtil.removeSnapshotListener();
            })

          Button("onSnapshotListener()-指定")
            .btnStyle()
            .onClick(() => {
   
              SnapshotUtil.onSnapshotListener(this.snapshotCallBack);
            })
          Button("removeSnapshotListener()-指定")
            .btnStyle()
            .onClick(() => {
   
              SnapshotUtil.removeSnapshotListener(this.snapshotCallBack);
            })

          Column() {
   
            Text("id组件截图1")
              .fontSize(16)
              .fontWeight(FontWeight.Bold)
              .fontStyle(FontStyle.Italic)
              .margin({
    top: 10 })
            Column() {
   
              Text("id组件截图2")
                .fontSize(12)
                .fontWeight(FontWeight.Bold)
                .fontStyle(FontStyle.Italic)
                .margin({
    top: 10 })
              Image($r("app.media.test_as3"))
                .margin({
    top: 10, bottom: 10 })
                .borderRadius(6)
            }
            .backgroundColor(Color.Pink)
            .borderRadius(10)
            .padding(10)
            .margin({
    top: 10 })
            .width('95%')
            .id('snapshot_id2')
          }
          .backgroundColor(Color.Brown)
          .border({
   
            width: 5,
            radius: 5,
            color: Color.Orange,
            style: BorderStyle.Dashed
          })
          .padding(10)
          .width('90%')
          .margin({
    top: 50 })
          .id('snapshot_id1')

          Blank().layoutWeight(1)
        }
        .margin({
    top: 5, bottom: 5 })
      }
      .layoutWeight(1)
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Start)
    .backgroundColor($r('app.color.main_background'))
  }

  @Builder
  RandomBuilder() {
   
    Column() {
   
      Text("Builder截图")
        .fontSize(20)
        .fontWeight(FontWeight.Bold)
        .fontStyle(FontStyle.Italic)
        .margin({
    top: 20 })
      Image($r("app.media.test_as4"))
        .margin({
    top: 30, bottom: 10 })
        .padding(10)
        .width('95%')
        .backgroundColor(Color.Pink)
    }
    .backgroundColor(Color.Blue)
    .padding(10)
    .width('100%')
    .aspectRatio(1)
    .margin({
    top: 50 })
    .id("rBuilder")
  }

}


@Styles
function btnStyle() {
   
  .width('90%')
  .margin({
    top: 10, bottom: 5 })
}

创作不易,请给童长老点赞👍


https://github.com/787107497/harmony-utils
https://gitee.com/tongyuyan/harmony-utils
OpenHarmony三方库

目录
相关文章
|
6月前
|
API Apache 开发者
最受欢迎的三方库之harmony-dialog
harmony-dialog 是一款简单易用的鸿蒙弹窗工具库,支持多种弹窗类型,如提示框、选择器、加载框、吐司等,满足多样化开发需求。一行代码即可调用,使用便捷,兼容 API12+。配合 harmony-utils 使用更佳,助力快速开发。
253 0
|
6月前
|
JSON 生物认证 API
harmony-utils之ArrayUtil,集合工具类
`harmony-utils` 是一款专为 HarmonyOS 开发的功能丰富工具库,提供如数组判空、去重、过滤、反转等操作,提升开发效率。
202 0
|
JSON 生物认证 API
harmony-utils之RegexUtil,正则工具类
RegexUtil 是 harmony-utils 中的正则工具类,提供多种常用正则验证方法,如验证手机号、邮箱、身份证、数字、URL 等。支持快速判断字符串是否匹配特定格式,助力 HarmonyOS 开发高效便捷。
200 0
|
6月前
|
iOS开发
harmony-dialog预览效果
harmony-dialog 是一款简单易用、零侵入的弹窗组件,支持多种类型如确认框、提示框、输入框、选择器、加载框等,覆盖常见开发需求。
214 0
harmony-dialog预览效果
|
存储 JSON 生物认证
harmony-utils之AssetUtil,关键资产存储服务工具类
AssetUtil 是 harmony-utils 工具库中的关键资产存储服务工具类,提供新增、查询、删除资产等功能,支持同步与异步操作,适用于 HarmonyOS 应用开发。
204 0
|
JSON API Apache
最受欢迎的三方库之china_area
`@nutpi/china_area` 是一款提供中国省、市、县三级区域数据的 OpenHarmony 工具库,支持同步与异步调用方式,便于快速集成至鸿蒙应用中。配套 `@pura/harmony-utils` 与 `@pura/harmony-dialog` 可实现高效开发,如地区选择器等交互功能。API 简洁易用,附有完整示例代码,助力开发者提升效率。项目遵循 Apache License 2.0 协议,欢迎参与共建。
202 0
|
6月前
|
API Apache Android开发
最受欢迎的三方库之harmony-web
`harmony-web` 是基于鸿蒙 WebView 构建的轻量级库,提供丰富的功能与问题解决方案,简化 WebView 开发。结合 `harmony-utils` 与 `harmony-dialog`,可快速构建高效、易用的鸿蒙应用。支持 ArkWeb 组件与多种配置选项,助力开发者高效实现网页加载、交互及弹窗功能。开源协议为 Apache License 2.0。
204 0
|
API Apache 开发者
最受欢迎的三方库之EventBus
EventBus 是一款支持 Sticky 和跨 App 广播的消息总线,适用于 HarmonyOS 开发。提供丰富的 API,如事件监听、消息发布等,助力高效构建应用。
223 0
|
JSON 生物认证 API
harmony-utils之JSONUtil,JSON工具类
harmony-utils之JSONUtil是一款HarmonyOS平台下的高效JSON处理工具类,支持JSON字符串与对象、数组、Map之间的相互转换,简化数据解析与操作,提升开发效率。
226 0
|
JSON 搜索推荐 生物认证
harmony-utils之ToastUtil,吐司工具类
harmony-utils 是一款功能强大的 HarmonyOS 工具库,包含丰富的工具类,如吐司(ToastUtil)、设备、通知、线程通信等,帮助开发者高效开发鸿蒙应用。支持快速集成与个性化配置,提升开发效率。
193 0